reading two MySql queries on c# - c#

SELECT #gb FROM parameters WHERE Form_Factor =#ff I'm new with c# and it's my first programm.
I'm trying to connect mysql server and run a query.
Then, I want to take he results of the first query and run another query with them.
the first query works good, the second mysqldataread doesnt work and i cant understand why. (i'm using vs 2013).
code:
myCommand.CommandText = "SELECT GB,Form_Factor FROM devices WHERE Serial_Number = #Sn";
myCommand.Parameters.AddWithValue("#Sn", Sn);
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
{
textBox2.Text = reader["GB"].ToString();
textBox3.Text = reader["Form_Factor"].ToString();
}
reader.Close();
connect.Close();
string gb = textBox2.Text;
string ff = textBox3.Text;
MySqlCommand myCommand2 = connect.CreateCommand();
myCommand2.Parameters.AddWithValue("#gb", gb);
myCommand2.Parameters.AddWithValue("#ff", ff);
myCommand2.CommandText = "SELECT #gb FROM parameters WHERE Form_Factor =#ff ";
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
reader2.Read();
if (reader2.Read())
{
string command = reader2["#gb"].ToString();
MessageBox.Show(command);
}
if (reader2.Read() == false)
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();

As I can guess #gb isn't an existing field in parameters table , thats why you aren;t getting any results in second query. Also using statement is a good practise when messing with sqlcommands:
myCommand2.CommandText = "SELECT #gb FROM parameters WHERE Form_Factor =#ff ";
myCommand2.Parameters.AddWithValue("#gb", gb);
myCommand2.Parameters.AddWithValue("#ff", ff);
using (connect)
{
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
while (reader2.Read())
{
string command = reader2[0].ToString();
MessageBox.Show(command);
}
}

You need to read more here or here.
However, I edit your code:
myCommand.CommandText = "SELECT GB,Form_Factor FROM devices WHERE Serial_Number = #Sn";
myCommand.Parameters.AddWithValue("#Sn", Sn);
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
{
textBox2.Text = reader["GB"].ToString();
textBox3.Text = reader["Form_Factor"].ToString();
}
reader.Close();
connect.Close();
string gb = textBox2.Text;
string ff = textBox3.Text;
myCOmmand.CommandText = #"SELECT * FROM parameters WHERE Form_Factor = 'Mercury';";
connect.Open();
MySqlDataReader reader2 = myCommand.ExecuteReader();
reader2.Read();
if (reader2.Read())
{
string command = reader2["columnName"].ToString();
MessageBox.Show(command);
}
if (reader2.Read() == false)
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();
Make sure to edit reader2["columnName"].TOString(); -> Edit columnName to the columnName you want to get.

1st - you dont need this line:
reader2.Read();
2nd - reader2["#gb"].ToString(); is wrong put the ColumnName you need instead of "#gb"
3rd - AddWithValue make no sense in this fall, you need it only if you have a dynamic variables in your sql-query
EDIT - second part:
string gb = textBox2.Text;
string ff = textBox3.Text;
MySqlCommand myCommand2 = connect.CreateCommand();
myCommand2.CommandText = "SELECT " + gb + " FROM parameters WHERE Form_Factor = #ff;";
myCommand2.Parameters.AddWithValue("#ff", ff);
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
if (reader2.Read())
{
string command = reader2[gb].ToString();
MessageBox.Show(command);
}
else
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();

Related

How to execute an update query while MysqlDataReader is running

I'm using C# console app to update a table with a lot of rows based on the value of two column inside MySQL.
Below is the code that I've tried to update the table.
Is it possible to execute update during dataread while loop or do I need to use other way to accomplish this?
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
Right now if I execute the programs, the data will not be updated and will show error
'There is already an open DataReader associated with this Connection which must be closed first.'
However if I close the connection, it will only execute and update the very first row which satisfy the if-else rule.
I think there must be a way for this to run in a loop without having me to run the program repeating times.
Can anyone suggest how should I fix the code for that?
U can define new connection object for that
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
MySqlConnection con1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con1);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
//I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
if(!rdr.read())
{
Console.WriteLine("Update query not working!!!");
}
else
{
//user_email
string usermail = Convert.ToString(user_email);
usermail = rdr[0].ToString();
Console.WriteLine("Username: {0}", usermail.ToString());
//meta_value AS 'Current Points'
string metavalue = Convert.ToString(meta_value);
metavalue = rdr[1].ToString();
Console.WriteLine("metavalue: {0}", metavalue.ToString());
//meta_value AS 'point'
string points = Convert.ToString(point);
points = rdr[2].ToString();
Console.WriteLine("point: {0}", points.ToString());
Console.ReadLine();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}

SQL Server cannot build connection string to db

I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project
string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";
string queryString = "SELECT * from tbclienti";
cn = new SQLConnection(s);
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
cn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
cn.Close();
I posted here whole code what could look like. Try it now.
string s = #"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";
using(SqlConnection cn = new SqlConnection(s))
{
string queryString = "SELECT * from tbclienti";
try
{
cn.Open();
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
}
catch(Exception ex)
{
// see if error appear
}
finally
{
cn.Close();
}
}

Exception: Invalid attempt to Read when reader is closed

I am trying to update my database while reading data from it, but the reader gets closed and it throws the exception that it can''t read wen reader is closed. Is the update.ExecuteNonQuery() closing the reader method?
If i get rid of linescon.Close(); con.Open(); i get There is already an open DataReader associated with this Connection which must be closed first.
So how can i update my database records while keep the reading opened?
{
public class MySqlReadUpdate
{
public int Id { get; set; }
public string Notes { get; set; }
}
static void Main()
{
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root; database=restaurants; pooling=false;SslMode=none;Pooling=True";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
con.Close();
con.Open();
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, con);
update.ExecuteNonQuery();
}
con.Close();
Console.WriteLine("Finished!");
Console.Read();
}
}
}
You cannot close a connection like you are, because the data reader depends on it. Once you call con.Close you break it. That's why you see an exception the next time it gets to reader.Read().
What you want is to add MultipleActiveResultSets=True in the configuration string; however, as we discussed in the comments it's apparently still not supported in MySQL. Therefore, the answer is two connection instances.
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root;database=restaurants;pooling=false;SslMode=none";
MySqlConnection con = new MySqlConnection(config);
MySqlConnection cmdCon = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
cmdCon.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, cmdCon);
update.ExecuteNonQuery();
}
con.Close();
cmdCon.Close();
Console.WriteLine("Finished!");
Console.Read();
I would recommend that you also modify your code to use using statements or wrap things in try-finally blocks.

how two get data from 2 different table c#

I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();

C# use a reader in another reader solution?

I need to get some mysql data into another mysql reader request anyway to workaround that I apparently can't have 2 readers open at the same time it will all end up in a datagrid
public void DBSelectPraktikanter(object sender)
{
string Command = "SELECT * FROM forlob WHERE firmaid = N'" + firmaid + "'";
MySqlConnection sqlConnection1 = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(Command, sqlConnection1);
sqlConnection1.Open();
MySqlDataReader reader = command.ExecuteReader();
var items = new List<praktikanter>();
if (reader.HasRows)
{
while (reader.Read())
{
string praktikantid = String.Format("{0}", reader["praktikantid"]);
string Command2 = "SELECT * FROM praktikanter WHERE id = N'" + praktikantid + "'";
MySqlCommand command2 = new MySqlCommand(Command, sqlConnection1);
MySqlDataReader reader2 = command.ExecuteReader();
if (reader.HasRows)
{
while (reader2.Read())
{
Praktikant = String.Format("{0}", reader["Navn"]);
}
}
string Fra = String.Format("{0}", reader["fra"]);
string Til = String.Format("{0}", reader["til"]);
items.Add(new praktikanter(Praktikant, Fra, Til));
}
}
sqlConnection1.Close();
var grid = sender as DataGrid;
grid.ItemsSource = items;
}
Instead of nesting MySqlCommands and looping the first resultset to query again the database to collect all of your data you should really use one query. Also use the using-statement to ensure that the connection gets closed even on error and use sql-parameters to avoid sql-injection issues:
var items = new List<praktikanter>();
string sql = #"SELECT p.*, f. Navn
FROM praktikanter p INNER JOIN forlob f ON p.id = f.praktikantid
WHERE f.firmaid = #firmaid";
using (var con = new MySqlConnection(connectionString))
using (var command = new MySqlCommand(sql, con))
{
command.Parameters.Add(new MySqlParameter("#firmaid", MySqlDbType.VarChar).Value = firmaid);
con.Open();
using (var rd = command.ExecuteReader())
{
while (rd.Read())
{
string praktikant = rd.GetString("Navn");
string fra = rd.GetString("Fra");
string til = rd.GetString("Til");
items.Add(new praktikanter(praktikant, fra, til));
}
}
}

Categories

Resources