Farrah Farrah - 4 months ago 24
SQL Question

How to store MySQL query result in a string

Is it possible to get MySQL query result in string variable. Consider the following scenario and let me know if it is possible to store MySQL query result into a string. 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). But my main concern for now is to get MySQL query result into a string.

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). 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? Your help would be really appreciated.
Thanks in Advance

Answer

There are a lot of problems in your code, to start, ExecuteNonQuery doesn't return rows. You need to use ExecuteReader, read one row, convert every field to a string, send it then repeat. But before this you need to fix that query, as is the i variable is not a value to filter your query. But really there is no need to call 20 times the same query filtering by ID, just use an appropriate WHERE condition

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