Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind parameters via ODBC C#?

Tags:

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

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 on ODBC?

like image 987
Emanuele Pavanello Avatar asked Aug 06 '13 14:08

Emanuele Pavanello


People also ask

How do I use ODBC parameters?

Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name. OdbcCommand cmd = conn. CreateCommand(); cmd.

How do you bind a parameter?

Bind parameters—also called dynamic parameters or bind variables—are an alternative way to pass data to the database. Instead of putting the values directly into the SQL statement, you just use a placeholder like ? , :name or @name and provide the actual values using a separate API call.

What is ODBC parameter?

You specify connection parameters when you create a data source or modify a data source connection.

What is binding an array?

Each data structure (array) contains all the data for a single parameter. This is called column-wise binding because it binds a column of values for a single parameter. Define a structure to hold the parameter data for an entire set of parameters and bind an array of these structures.


1 Answers

Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name.

OdbcCommand.Parameters

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

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

You have also another problem, the USER word is a reserved keyword per MS Access Database and if you want to use that as field name or table name then it is required to enclose every reference with square brackets. I strongly suggest, if it is possible, to change that table name because you will be hit this problem very often.

like image 121
Steve Avatar answered Oct 04 '22 04:10

Steve