AS400 SQL query with Parameter

风格不统一 提交于 2019-11-29 15:53:00
Picflight

Ok, I got the solution by playing around and trying different things.

As I said before, I am used to OLEDB and ADO.Net so I am used to doing things like:

Select FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = @Field1

which work in Access and SQL Server but not in AS/400.

I got the following to work:

Select FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = ?

cmd.ActiveConnection = connstr
cmd.CommandType = 1'4   'Stored Procedures '1 Text
cmd.CommandText = sql
Set Param1 = cmd.CreateParameter("@Field1", 129, 1, 9, "myvalue")  ' 129 String
cmd.Parameters.Append Param1
Set rs = cmd.Execute()

This is all VbScript. The trick was to add the question mark(?) in the sql statement.

If you're going to connect to the AS400 using .NET, first of all you should use the IBM.Data.DB2.iSeries .NET provider from IBM. According IBM's documentation, this is the preferred method for calling sql:

iDB2Connection conn = new IDB2Connnection(connectionstring);
iDB2Command cmd = null;

try
{
  conn.Open();
  string sql = "select * from somelibrary.sometable where a = @A and b = @B";
  cmd = conn.CreateCommand();
  cmd.CommandText = sql;
  cmd.DeriveParameters(); //this will talk to the AS400 to determine the param types
  cmd.Parameters["@A"].Value = Avalue;
  cmd.Parameters["@B"].Value = Bvalue;

  //execute the query
  cmd.ExecuteScalar(); //doesn't have to be Scalar but you get the idea
}
catch (Exception ex)
{
   //handle your exceptions
}
finally
{
  cmd.Dispose();
  conn.Close();
}

Picflight,

You might have connected using the system naming conventions instead of SQL naming conventions. Change Mylibrary.Mytable (SQL period qualifier) to Mylibrary/Mytable (system slash qualifier).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!