C#使用参数访问数据库选择

时间:2016-03-08 11:35:32

标签: c# sql

我在访问数据库中使用参数执行查询时遇到问题:

OleDbConnection cnn;
OleDbCommand cmdselect2;
string sqlselect2 = null;
string baza = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + @"L:\Windykacja\Sdro\Projekt\projekt.accdb";
connetionString = baza;
sqlselect2 = "SELECT count(POS_Pesel_regon) as Suma FROM POS WHERE POS_Pesel_regon = @PR";
cnn = new OleDbConnection(connetionString);
cnn.Open();
cmdselect2 = new OleDbCommand(sqlselect2, cnn);
Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());
cmdselect2.Parameters.AddWithValue("@PR", textBox6.Text);
cmdselect2.Dispose();
cnn.Close();

据说我的参数缺失了

在插入中它完美地工作:)

感谢任何消息。

欢呼声

1 个答案:

答案 0 :(得分:2)

因为您尝试在之前执行命令,所以添加参数。改变这些行

Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());
cmdselect2.Parameters.AddWithValue("@PR", textBox6.Text);

cmdselect2.Parameters.AddWithValue("@PR", textBox6.Text);
Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());

还有一些事情;

using(var cnn = new OleDbConnection(connetionString))
using(var cmdselect2 = cnn.CreateCommand())
{
   cmdselect2.CommandText = @"SELECT count(POS_Pesel_regon) as Suma FROM POS 
                              WHERE POS_Pesel_regon = @PR";
   cmdselect2.Parameters.Add("@PR", OleDbType.VarChar).Value = textBox6.Text;
   // I assumed your column type as VarChar
   cnn.Open();
   int PR1 = (int)cmdselect2.ExecuteScalar();
}