C#MySQLDataReader为所有行返回相同的字符串

时间:2019-02-24 16:40:58

标签: c# mysql sql

我正在尝试从表中提取值,而MySQLDataReader似乎不想与我合作。

handleClick = (placement, index) => event => {     // i renamed the second param to index
    const { currentTarget } = event
    this.setState(state => ({
      anchorEl: {
        ...state.anchorEl,                         // keep the anchorEl for other indices same
        [index]: currentTarget,                    // only change this one
      },
      open: {
        ...state.open,                             // keep the other popper as they were
        [index]: !state.open[index],               // toggle only this one
      },
      placement: {
        ...state.placement,                        // keep the others same
        [index]: placement,                        // update placement for this one
      },
    }))
  }

conn = new MySqlConnection(Credentials); conn.Open(); MySqlCommand cmd = new MySqlCommand(), cmd2 = new MySqlCommand(); cmd.Connection = conn; cmd2.Connection = conn; cmd.CommandText = "SELECT * FROM test"; cmd2.CommandText = "INSERT INTO test (test) VALUES (1),(2),(3),(4),(5),(6),(8);"; cmd2.ExecuteNonQuery(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.ToString()); } conn.Close(); 可以正常工作,因为在检查表后,该表已用数字1-8填充,但这是

INSERT

在控制台中返回

while (reader.Read())
{
    Console.WriteLine(reader.ToString());
}

1 个答案:

答案 0 :(得分:5)

您需要访问SqlDataReader的列。您可以阅读Retrieve data using a DataReader。当前代码仅在阅读器上调用ToString(),它只是返回其类型。

您可以通过以下方式提取数据:

reader.GetString(0)     // get a string in the first column
reader.GetInt32(1)      // get an integer in the second column
reader.GetValue(2)      // get an object in the third column
reader.GetDateTime(3)   // get a datetime   
reader.GetDouble(4)     // get a double

// or by index/indexing
reader["ColumnName"].ToString()  // get value by column name
reader[0].ToString()             // get value by index

因此您的代码将变为:

while (reader.Read())
{
    // get the value from the first column
    Console.WriteLine(reader.GetInt32(0));    
}