How to bind parameters through ODBC C #?

I need to bind parameters to an ODBC query from C #. This is sample code, but VS tells me that one parameter is missing there.

OdbcCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM user WHERE id = @id"; cmd.Parameters.Add("@id", OdbcType.Int).Value = 4; OdbcDataReader reader = cmd.ExecuteReader(); 

What is the syntax for binding values ​​for ODBC?

+12
c # parameters odbc
Aug 6 '13 at 14:21
source share
2 answers

Odbc cannot use named parameters. This means that command line uses placeholders for each parameter, and this placeholder is the only question mark, not the parameter name.

OdbcCommand.Parameters

Then you need to add the parameters to the collection in the same order in which they appear on the command line

 OdbcCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM [user] WHERE id = ?"; cmd.Parameters.Add("@id", OdbcType.Int).Value = 4; OdbcDataReader reader = cmd.ExecuteReader(); 

You also have another problem: the word USER is a reserved keyword for MS Access Database, and if you want to use it as a field name or table name, then you need to enclose each link in square brackets. I highly recommend, if possible, changing this table name because you will encounter this problem very often.

+26
Aug 6 '13 at 14:25
source share

use "?" instead of @ if you are using ODBC.

Try the following:

 OdbcCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM user WHERE id = ?"; cmd.Parameters.Add("@id", OdbcType.Int).Value = 4; OdbcDataReader reader = cmd.ExecuteReader(); 
+6
Aug 6 '13 at 14:24
source share



All Articles