读者没有显示任何搜索数据?

时间:2014-12-15 11:03:41

标签: c# sql

当执行到while(reader.read())部分时,这个代码示例..它没有进入循环并显示该查询没有任何数据。我已经尝试了评论中的东西......它也没有成功。建议我在这段代码中出错了什么?

string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
    connection.Open();

    SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =" + " '" + "@TableName" + "'", connection);
    // SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ActivityIndex';
    command.Parameters.Add("@TableName", SqlDbType.NVarChar).Value = listSelectTable.Text;

    //SqlCommand command = new SqlCommand();
    //command.CommandType = CommandType.Text;
    //command.Connection = connection;
    //command.CommandText = String.Format("SELECT [column_name] FROM information_schema.columns WHERE table_name = '{0}'", listSelectTable.Text);


    /*using (command)
    {*/
        listSelectColumn.Items.Clear();
        using (SqlDataReader reader = command.ExecuteReader())
        {

            while (reader.Read())
            {
                listSelectColumn.Items.Add((string)reader["COLUMN_NAME"]);
            }
            listSelectColumn.Items.Add("ALL");
        }
    /*}*/
    connection.Close();
}

3 个答案:

答案 0 :(得分:0)

试试这个: -

SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
                                 WHERE TABLE_NAME =@TableName", connection);

您无需在查询中添加引号,因为您在命令参数中指定了引号。此外,您无需使用已注释的代码,因为默认情况下您指定Connection' & 'CommandType是文本。

答案 1 :(得分:0)

单独传递参数时无需装饰。

string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(constr))
        {
            connection.Open();

            SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =@TableName", connection);            
            command.Parameters.Add("@TableName", SqlDbType.NVarChar).Value = listSelectTable.Text;


                listSelectColumn.Items.Clear();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        listSelectColumn.Items.Add((string)reader["COLUMN_NAME"]);
                    }
                    listSelectColumn.Items.Add("ALL");
                }

            connection.Close();
        }

答案 2 :(得分:0)

尝试按如下方式修改代码

SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName" , connection);
command.Parameters.Add("@TableName", SqlDbType.NVarChar);
command.Parameters["@TableName"].Value = listSelectTable.Text;