如何在sql查询中传递动态值
本文关键字:动态 查询 sql | 更新日期: 2023-09-27 18:24:41
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);
string st = ("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no =" + i);
首先,您应该使用参数重写您的语句
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;
发送参数化查询时,应使用SqlParameter
。有关如何使用它们的示例,请访问http://www.dotnetperls.com/sqlparameter
基本上,您可以使用占位符构建查询,并使用SqlCommands 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())
{
}
}
}
string st = string.Format("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = {0}",i);