0

我的 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();

所以它应该从 tbl1 返回属于 Bob 的所有汽车。查询只返回一个字符串并将其放入列表框“ddl1”,而它应该至少返回其中的 3 个。有任何想法吗?

4

3 回答 3

3

您需要遍历阅读器:

while (rd.Read()){
   ddl1.Items.Add(rd.GetValue(0).ToString());
}
于 2012-11-23T19:16:16.940 回答
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());
            }
        }
    }
}
于 2012-11-23T20:02:53.953 回答
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();
于 2012-11-23T20:15:35.070 回答