如何在MessageBox()中显示从MS Access中选择的数值?

时间:2015-08-29 06:36:30

标签: c# oledb

为什么我的代码会显示消息

  

标准表达式中的数据类型不匹配。

我的代码:

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;

string cq = "select sum(Fine) from studentbook where S_ID=" + textSID.Text + "";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteReader());
connection.Close();
MessageBox.Show(a.ToString());

1 个答案:

答案 0 :(得分:1)

更改此代码:

where S_ID = '" + textSID.Text + "'

同时使用command.ExecuteScalar()代替command.ExecuteReader()

int a = Convert.ToInt32(command.ExecuteScalar());

顺便说一下,您应该始终使用parameterized queries。这种字符串连接对SQL Injection开放。