从数据库中选择查询
本文关键字:查询 选择 数据库 | 更新日期: 2023-09-27 18:20:01
我认为一切都很好,为什么数据没有显示在文本框中。我用了很多次这个代码。那么这里有什么错误呢?我在Visual Studio 2012工作。
string name = comboBox1.SelectedIndex.ToString();
query = "select *from Record Where Name='"+name+"'";
cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text =(dr["Items1"].ToString());
textBox2.Text = (dr["Items1_Charge"].ToString());
textBox3.Text = (dr["Items2"].ToString());
textBox4.Text = (dr["Items2_Charge"].ToString());
textBox5.Text = (dr["Items3"].ToString());
textBox6.Text = (dr["Items3_Charge"].ToString());
textBox7.Text = (dr["Items4"].ToString());
textBox8.Text = (dr["Items4_Charge"].ToString());
}
我怀疑*from应该是*from。此外,我建议使用如下所示的where条件的参数,尤其是当有可能嵌入撇号时。另外请注意,我添加了HasRows,所以我们确信有什么东西回来了。我还更改了从ComboBox 获取当前值的方式
public void Sample()
{
string name = comboBox1.Text;
query = "select * from Record Where Name= @Name";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textBox1.Text = (dr["Items1"].ToString());
textBox2.Text = (dr["Items1_Charge"].ToString());
textBox3.Text = (dr["Items2"].ToString());
textBox4.Text = (dr["Items2_Charge"].ToString());
textBox5.Text = (dr["Items3"].ToString());
textBox6.Text = (dr["Items3_Charge"].ToString());
textBox7.Text = (dr["Items4"].ToString());
textBox8.Text = (dr["Items4_Charge"].ToString());
}
}
}