如何在sql查询中传递动态值

时间:2014-09-27 07:17:16

标签: c#

int i = int.Parse(rid);
SqlConnection thisconnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True");
thisconnection.Open();
string st = ("select  receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = 4");
DataSet thisdataset = new DataSet();
//string cmdtext = "select * from receipt_info where receipt_no =='" + i + "'";
SqlCommand cmd = new  SqlCommand(st, thisconnection);
SqlDataAdapter data_ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
data_ad.Fill(dt);

4 个答案:

答案 0 :(得分:0)

string st = string.Format("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = {0}",i); 

答案 1 :(得分:0)

首先,您应该使用参数

重写您的语句
string st = "select  receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = @Receipt_Number";

当你创建了SqlCommand时 - 你应该为它添加@Receipt_Number参数

cmd.Parameters.Add("@Receipt_Number", SqlDbType.Int);
cmd.Parameters["@Receipt_Number"].Value = i;

答案 2 :(得分:0)

发送参数化查询时,您应该使用SqlParameterhttp://www.dotnetperls.com/sqlparameter

提供了如何使用它们的示例

基本上,您使用占位符构建查询,并使用SqlCommand s Parameters属性填充它们。

int searchId = 4;
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True"
using (SqlConnection connection = new SqlConnection(connectionString)) {
    connection.Open();
    using (SqlCommand command = new SqlCommand(
        "select  receipt_no, name, rupees, pay_by, date " +
        "from receipt_info where receipt_no = @Id", connection))
    {
        command.Parameters.Add(new SqlParameter("Id", searchId));
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
        }
    }
}

答案 3 :(得分:0)

string st = ("select  receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no =" + i);