Using Parameters with OleDbDataAdapter in C#

倖福魔咒の 提交于 2020-01-05 03:36:10

问题


I'm using OleDb to populate a DataTable. I'm trying to use a parameterized query, but it doesn't seem to work with a OleDbDataAdapter. Anyone have any suggestions?

cmd.CommandText = "SELECT A,B,C,D FROM someTable WHERE A=@A AND D BETWEEN @D1 AND @D2";
cmd.Parameters.Add("@A", OleDbType.VarChar).Value = "1234567";
cmd.Parameters.Add("@D1", OleDbType.DBDate).Value = "02/01/2011";
cmd.Parameters.Add("@D2", OleDbType.DBDate).Value = "01/31/2012";

A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
System.Data.OleDb.OleDbException (0x80040E11): [DB2] SQL0206N  "@A" is not valid in the context where it is used.  SQLSTATE=42703

回答1:


See http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter.aspx:

"The OLE DB.NET Framework Data Provider uses positional parameters that are marked with a question mark (?) instead of named parameters."

So you cannot use the @Parameter syntax, you have to indicate parameters with question marks, and assign your parameter values in the exact same sequence as they appear in the query.




回答2:


For those looking for help when their query doesn't even have a parameter, check if your column names are valid.

see @TheTerribleProgrammers answer at OleDbException: no value given for parameters when no parameters are defined




回答3:


public static DataTable getDataGridList(string strCmd)
    {

        openConnection(conn);
        OleDbDataAdapter DADet = new OleDbDataAdapter(strCmd, conn);
        DataTable DTDet = new DataTable();
        DADet.Fill(DTDet);
        closeConnection(conn, null);
        return DTDet;
    }


来源:https://stackoverflow.com/questions/8123507/using-parameters-with-oledbdataadapter-in-c-sharp

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