用户单击btnAdd
,然后将项目转移到listBox1
。现在,我想创建一个查询,该查询创建一个从listBox1
到SQL中的表SELECT FROM
的循环,并将结果项添加到listBox2
我有此示例代码,但无法正常工作。有人可以帮我吗?
public void add()
{
var con = new DBConnection();
try
{
for (int i = 0; i < listBServices.Items.Count; i++)
{
SqlCommand cmd = new SqlCommand("SELECT price FROM price WHERE service = '" +
listBServices.Items.ToString() + "';", con.Connection);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
int price = rd.GetInt32(0);
listBPrice.Items.Add(price.ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我得到这个证据:
答案 0 :(得分:1)
检查您的连接,然后使用“使用代码”块自动关闭连接。
svn status --show-updates
答案 1 :(得分:1)
片刻之后您应该关闭阅读器
public void add()
{
var con = new DBConnection();
try
{
for (int i = 0; i < listBServices.Items.Count; i++)
{
SqlCommand cmd = new SqlCommand("SELECT price FROM price WHERE service = '" +
listBServices.Items.ToString() + "';", con.Connection);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
int price = rd.GetInt32(0);
listBPrice.Items.Add(price.ToString());
}
rd.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 2 :(得分:1)
listBServices.Items.ToString()
产生字符串"System.Windows.Forms.ListBox+ObjectCollection"
。您必须使用
SqlCommand cmd = new SqlCommand("SELECT price FROM price WHERE service = '" +
listBServices.Items[i] + "'",
con.Connection);
但是使用字符串连接不是一个好主意。请改用参数。
SqlCommand cmd = new SqlCommand("SELECT price FROM price WHERE service = @svc",
con.Connection);
cmd.Parameters.Add("@svc", SqlDbType.NVarChar).Value = listBServices.Items[i];