背景
我编写了一个函数,它使用 SQL 查询检索数据,然后将该数据输出到标签。目前,搜索字符串被硬编码为“1002”。该函数在按钮单击事件上触发。
问题
如何将数据从文本框传递到我的 SQL 查询中,以便我的搜索字符串是文本框的内容,而不是 1002?
代码
private void getInfoStationID()
{
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = 1002";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, ConnStr);
DataSet question = new DataSet();
Adpt.Fill(question);
foreach (DataRow dr in question.Tables[0].Rows)
{
nameTtb.Text += question.Tables[0].Rows[0]["stationname"].ToString();
}
}
请您参考如下方法:
将查询更改为:
string constring = @""; // Declare your connection string here.
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = @StationId";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand command = new SqlCommand(SQL ,con);
然后您必须像这样向命令对象添加参数:
command .Parameters.Add("@StationId",SqlDbType.NVarChar).Value = textbox.Text;
现在您可能想知道为什么我在查询中使用了参数。这是为了避免 SQL 注入(inject)。
DataSet ds = new DataSet();
SqlDataAdapter adb = new SqlDataAdapter(command);
adb.Fill(ds);
con.Close();
现在您可以像这样迭代...
foreach (DataRow row in ds.Tables[0].Rows)
{
}
并且您必须初始化连接对象并在其中传递您的连接字符串。
