简体   繁体   English

如何将MySQL查询结果存储在字符串中

[英]How to store MySQL query result in a string

Is it possible to get MySQL query result in string variable. 是否有可能在字符串变量中获取MySQL查询结果。 Consider the following scenario and let me know if it is possible to store MySQL query result into a string. 考虑以下情况,让我知道是否可以将MySQL查询结果存储到字符串中。 My Database is as follows 我的数据库如下

Article ID       Article Name    Article Quantity
1                Article1         15 Units
2                Article2         20 Units
3                Article3         18 Units

Furthermore I am trying to access rows one by one using for loop (don't know whether I am doing it right or wrong way). 此外,我试图使用for循环一一访问行(不知道我是对还是错)。 But my main concern for now is to get MySQL query result into a string. 但是我现在主要关心的是将MySQL查询结果转换成字符串。

private void send_serial_data(string port_name)
{
    MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
    SerialPort sp = new SerialPort(port_name, 9600, Parity.None, 8, StopBits.One);
    MyConn2.Open();
    sp.Open();
    string variable; //In which I want to store Query
    int j = 0; //To keep track of null rows
    {
        for (int i = 1; i < 20; i++) //I is defined to select new row each time
        {
            String Query = "";
            Query = "SELECT * FROM warehouse_data.display where Article_ID= i";
            MySqlCommand cmd = new MySqlCommand(Query, MyConn2);
            // variable = (string)command.ExecuteScalar();    Tried this to save query but doesn't work.
            int a = cmd.ExecuteNonQuery();
            if (a == 0)
            {
                j++;
                if (j >= 10)
                {
                    MessageBox.Show("Data Transmitted Successfully");
                    break;
                }
            }
            else
            {
                sp.Write(variable); //variable in which I want to store MySQL query
                System.Threading.Thread.Sleep(5000);
            }
        }
    }
}

Basically I am trying to send MySQL data onto serial port (one row at a time). 基本上,我试图将MySQL数据发送到串行端口(一次一行)。 Any suggestions on how to save query into defined string 'variable' and how to use for loop to achieve my goal or any other way to effectively access rows one by one? 关于如何将查询保存到定义的字符串“变量”中以及如何使用for循环实现我的目标或任何其他有效地逐行访问方式的建议? Your help would be really appreciated. 您的帮助将不胜感激。 Thanks in Advance 提前致谢

There are a lot of problems in your code, to start, ExecuteNonQuery doesn't return rows. 首先,您的代码中存在很多问题,ExecuteNonQuery不返回行。 You need to use ExecuteReader, read one row, convert every field to a string, send it then repeat. 您需要使用ExecuteReader,读取一行,将每个字段转换为字符串,发送然后重复。 But before this you need to fix that query, as is the i variable is not a value to filter your query. 但是在此之前,您需要修复该查询,因为i变量不是用于过滤查询的值。 But really there is no need to call 20 times the same query filtering by ID, just use an appropriate WHERE condition 但是实际上,不需要使用ID调用相同查询过滤的20次,只需使用适当的WHERE条件

private void send_serial_data(string port_name)
{
    using (MySqlConnection MyConn2 = new MySqlConnection(MyConnection2))
    using (SerialPort sp = new SerialPort(port_name, 9600, Parity.None, 8, StopBits.One))
    {
        MyConn2.Open();
        sp.Open();

        // A query that returns all records with an ID lower than 20
        String Query = @"SELECT * FROM warehouse_data.display where Article_ID < 20";
        using (MySqlCommand cmd = new MySqlCommand(Query, MyConn2))
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            // Read one record 
            while (reader.Read())
            {

                StringBuilder sb = new StringBuilder();
                // Accumulate the fields values in the stringbuilder
                // separating each one with a comma
                for (int x = 0; x < reader.FieldCount; x++)
                {
                    if (reader.IsDBNull(x))
                        sb.Append(",")
                    else
                        sb.Append(reader[x].ToString() + ",");
                }
                // trim away the last comma
                sb.Length--;

                // And probably you need something to separate a record
                // from the following one. For example a newline
                sb.Append(Environment.NewLine);

                // send it along the wire
                sp.Write(sb.ToString());
            }
        }
    }
}

Note also two other things, I have separated each field with a comma, otherwise the receiver of your write to the serial port will be unable to reconstruct the fields read from the table, also every disposable object should be enclosed in an appropriate using statement 还要注意另外两件事,我用逗号分隔了每个字段,否则,您写入串行端口的接收方将无法重构从表中读取的字段,而且每个可抛弃的对象都应包含在适当的using语句中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM