我有一个 SQL Server 数据库文件 MsUser.mdf
,其中的表 MsAccount
有 5 列:
userID accountID accountName accountBalance imageLocation
我需要找到 accountBalance
,其中 accountID = combobox
被选中,并将其显示在 labelBalance._text
中。 AccountBalance
是decimal
,accountID
是varchar(10)
。
我在 comboBox 事件选择索引处编写了代码。 感谢您的帮助。
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = comboBox2.SelectedItem.ToString();//typ0000001-cake
int position = selected.IndexOf("-");
string accountID = selected.Substring(0,position);//typ0000001
SqlDataAdapter sdaUserID = new SqlDataAdapter("Select Count(accountBalance),accountBalance From MsAccount where accountID='" +accountID+"'", cn);
DataTable dt1 = new DataTable();
sdaUserID.Fill(dt1);
lblBalance.text = dt1.Rows[0][1].ToString();
}
最佳答案
很高兴您的代码可以正常工作。一般来说,最好创建一个参数化查询,但如果安全不是主要问题,那么只需一个普通的 select SQL 字符串就可以完成这项工作(就像你的情况一样)。
关于一些性能优化的几句话:我建议使用 String.Concat(string1, string2)
而不是 string1+string2
方法,因此最好是修改代码中的行,如下所示:
SqlDataAdapter sdaUserID = new SqlDataAdapter(String.Concat ("Select Count(accountBalance),accountBalance From MsAccount where accountID='",accountID, "'"), cn);
最好的问候,
关于c# - 如何在 .mdf 数据库上执行参数化选择查询并显示列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27957158/