使用流读取器捕获sql语句返回的值c#

时间:2013-09-02 07:56:06

标签: c# asp.net sql multiple-instances

伙计们,我有一个返回1个以上值的SQL语句。 我正在尝试使用StreamReader将值转换为数组,如下所示

 string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME=' " + table + "' and CONSTRAINT_NAME like 'PK_%'";
            SqlConnection conn2 = new SqlConnection(cnstr.connectionString(cmbDatabase.Text));
            SqlCommand cmd_server2 = new SqlCommand(sql);
            cmd_server2.CommandType = CommandType.Text;
            cmd_server2.Connection = conn2;
            conn2.Open();

            //reader_sql = new StreamReader();
            SqlDataReader reader_sql = null;
            string[] colName = new string[200];
            reader_sql = cmd_server2.ExecuteReader();
            while (reader_sql.Read());

            for (int rr = 0; rr < 20; rr++)
            {
                colName[rr] = reader_sql["COLUMN_NAME"].ToString();
            }

它不起作用,我做错了什么人?

3 个答案:

答案 0 :(得分:3)

你有一个迷路;将你的while变成一个紧凑的循环,所以请尝试:

        while (reader_sql.Read())

        for (int rr = 0; rr < 20; rr++)
        {
            colName[rr] = reader_sql["COLUMN_NAME"].ToString();
        }

答案 1 :(得分:2)

也许您应该在阅读结束时删除分号

while (reader_sql.Read())
{
    for (int rr = 0; rr < 20; rr++)
       colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}    

但是,如果您打算检索属于主键的列,则代码错误,因为您添加了相同主键列的20倍,然后对以20个字符串数组结尾的其余列重复相同的操作等于主键集中的最后一列。我认为您应该更改代码以使用List(Of String)而不是固定长度数组,并让读取器在检索到的主键列上正确循环

List<string> pks = new List<string>();
while (reader_sql.Read())
{
    pks.Add(reader_sql["COLUMN_NAME"].ToString());
}    

编辑:我刚刚注意到您的查询在表名前面包含一个空格。字符串连接然后生成一个无效的表名,该查询在语法上是正确的但不返回任何数据

string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " + 
             "where TABLE_NAME='" + table + "' and CONSTRAINT_NAME like 'PK_%'";
                                ^ space removed here

当你在它时,删除字符串连接并使用参数化查询.....

string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " + 
             "where TABLE_NAME=@tName and CONSTRAINT_NAME like 'PK_%'";
SqlCommand cmd_server2 = new SqlCommand(sql, connection);
connection.Open();
cmd_server2.Parameters.AddWithValue("@tName", table);

答案 2 :(得分:2)

你得到了例外,因为

while (reader_sql.Read());

应该是

while (reader_sql.Read())
{
    for (int rr = 0; rr < 20; rr++)
     {
         colName[rr] = reader_sql["COLUMN_NAME"].ToString();
     }
}