如何在c#中读取mysql中的特定列和单元格?

时间:2013-04-09 14:13:55

标签: c# mysql select executereader

我使用ExecuteReader为所有字段选择所有(SELECT *),如此

string query = "SELECT* FROM tb_patient_information ";
        if (this.OpenConnection() == true)
        { //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);
            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();
            while (dataReader.Read())
            { ... }

但我只想选择特定的列和单元格,如红色方块..就像这张图片I only want to select in specific cell&column like in red square

4 个答案:

答案 0 :(得分:3)

您可以在while子句中获取特定列。

while (dataReader.Read())
{ 
    var _column = dataReader["Nama_Kategori"];
}

答案 1 :(得分:1)

考虑使用

        string query = "SELECT column FROM tb_patient_information ";
        if (this.OpenConnection() == true)
        { 
            //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);
            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();
            if (dataReader.Read())
            { 
                dataReader.ExecuteScalar();
             }
        }

或使用dataReader["columnName"]

答案 2 :(得分:1)

您可以使用ExecuteScalar()的SqlCommand方法来检索单个值

MySqlCommand myCommand = new MySqlCommand("SELECT Nama_Kategori FROM tb_patient_information WHERE Id_kategori = 'KI-02'", myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();

答案 3 :(得分:0)

SQL查询

如果您只想要第三行数据,请尝试以下查询:

Select * from (Select row_number() over (order by subssn) as rownum, * FROM 
tb_patient_information)result Where rownum = 3

- 此查询返回结果集

上的第3行

在DataReader中

while (dataReader.Read())
{ 
string Id = dataReader["Id_kategori"].ToString();
string Name = dataReader["Nama_Kategori"].ToString();
}

如果你说我只使用Select * from tb_patient_information而我需要第三行结果然后尝试如下

         int count=1;  
         while (dataReader.Read())  
          {  

            if(count == 3)
            {
             string Id = dataReader["Id_kategori"].ToString();
             string Name = dataReader["Nama_Kategori"].ToString();
            }  
           count ++;  
          }