2014-09-24 132 views
-1

以下代码用于将数据从excel读取到gridview中。OleDbAdapter在查询中不识别'@'

String cusid1 = maskedTextBox1.Text.ToString(); 
string s = "provider=Microsoft.Jet.OLEDB.4.0;data source=c:xxx.xls;Extended Properties=Excel 8.0;"; 
OleDbConnection con = new OleDbConnection(s); // connection string 
con.Open(); 
string strQuery = "select * from [test$] where cusid = @cusid1"; 
OleDbDataAdapter da = new OleDbDataAdapter(strQuery, con); 

//Or Use OleDbCommand 
DataSet ds = new DataSet(); 
da.Fill(ds); 
dataGridView1.DataSource = ds.Tables[0]; 

conn.Open(); 

但当代替@cusid1select * from [test$] where cusid=1指定一个数字,我收到正确的输出。如果我在查询中使用@cusid,则会出现此错误:

No value given for one or more required parameters.

+5

您不添加'@ cusid1'参数到命令的任何地方 – user2711965 2014-09-24 13:32:05

+0

你预计到设置'@ cusid1值'' – 2014-09-24 13:33:36

回答

1

您应该传入参数。另外,命名参数在OLEDB中不做任何事情。他们被忽略。改为使用?

MSDN

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement

的代码,你需要:

string strQuery = "select * from [test$] where cusid = ?"; 

OleDbCommand command = new OleDbCommand(sqlQuery, conn); 
command.Parameters.AddWithValue("?", cusid); 

da.SelectCommand = command; 
+0

问题解决了很多。 – amar 2014-09-24 15:39:32