我有两个由combobox.text
设置的参数化变量,由最终用户选择。
尝试使用使用参数化变量的查询时,我收到以下错误。
附加信息:必须声明标量变量“@username”
我错过了什么吗?
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = @username and status = @status";
//Decide what query
String SQL = SQLSelection();
//Connection String
String ConnString = "Data Source=dbsqlexpress; Provider=SQLOLEDB; Initial Catalog=Data; User ID=mobile; Password=PW";
//Create and initalize Oledbconnection object and pass connection string into it.
OleDbConnection con = new OleDbConnection(ConnString);
//open connection to database
con.Open();
//create adapter that sits inbetween dataset and datbase
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(SQL,con);
adapter.SelectCommand.Parameters.Add("@username", OleDbType.VarChar).Value = auditorCmb.Text;
adapter.SelectCommand.Parameters.Add("@status", OleDbType.VarChar).Value = statusCmb.Text;
//Create dataset
DataSet dataset = new DataSet();
using (DataTable dt = new DataTable())
{
adapter.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
dataGridView1.DataSource = dt;
int rowCount = rowCount = dt.Rows.Count;
label10.Text = rowCount.ToString("n0");
}
}
答案 0 :(得分:4)
使用OLE DB(和ODBC),您需要在SQL语句中将?
指定为参数标记。然后根据顺序参数将这些映射到映射到集合。
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = ? and status = ?;";
避免在.NET应用程序中使用OLE DB和ODBC。 .Net Provider for SQL Server
(a.k.a SqlClient)将提供.Net应用程序的更好性能。此外,Microsoft已宣布弃用OLE DB以便在SQL Server中进行关系数据库访问。
答案 1 :(得分:1)
当CommandType设置为Text时,OLE DB .NET提供程序不支持将参数传递给SQL语句或OleDbCommand调用的存储过程的命名参数。在这种情况下,必须使用问号(?)占位符。例如:
SELECT * FROM Customers WHERE CustomerID =?