我的SQL查询有问题。
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
rd.Read();
ddl1.Items.Add(rd.GetValue(0).ToString());
conn.Close();
所以它应该从属于Bob的tbl1返回所有车辆。查询只返回一个字符串并将其放入Listbox“ddl1”,而它应至少返回3个字符串。 有什么想法吗?
答案 0 :(得分:3)
您需要遍历读者:
while (rd.Read()){
ddl1.Items.Add(rd.GetValue(0).ToString());
}
答案 1 :(得分:0)
Novak,不确定Curt解决方案的问题是什么,因为它是正确的。您的完整陈述应如下所示:
string connectionString= "Data Source=.\\SQLExpress;Trusted_Connection=True;User Instance=True;AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string query = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ddl1.Items.Add(reader.GetValue(0).ToString());
}
}
}
}
答案 2 :(得分:0)
尝试以下代码:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
ddl1.DataSource = rd;
ddl1..DataTextField = "columnname"; //your column name
ddl1.DataValueField = "columnname";
ddl1.DataBind();
rd.Close();
conn.Close();