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();
}
Related
I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}
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();
How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.
I'm getting this error
This method or property cannot be called on Null values
on this line id = rd.GetString(0);. How to solve it?
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read()){
id = rd.GetString(0);
}
con.Close();
return id;
}
add this
!rd.IsDBNull(0)
before
id = rd.GetString(0);
So, your code would look like
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
if(!rd.IsDBNull(0))
id = rd.GetString(0);
}
con.Close();
return id;
I am trying to take a single value from a database, but the cycle does not seem to start at all?
if (connection.State == ConnectionState.Open)
{
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
value = dataReader["amount"].ToString();
}
dataReader.Close();
connection.Close();
}
These are the commands:
public string value;
public static string Konekcija = "Server=127.0.0.1; Database=CardIgrica; Uid=admin; Pwd=admin;";
public string komanda = "SELECT amount FROM CardIgrica.creaures WHERE id = '1';";
MySqlConnection connection = new MySqlConnection(Konekcija);
MySqlCommand cmd = new MySqlCommand(komanda, connection);
connection.Open();
try this for the select
public string value {get; set;}
string komanda ="SELECT amount FROM CardIgrica.creaures WHERE id = 1";
Try this
using (SqlConnection conn = new SqlConnection(Konekcija))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.CommandText = komanda ;
conn.Open();
var dataReader= cmd.ExecuteReader();
while (result.Read())
{
value = dataReader["amount"].ToString();
}
conn.Close();
}
If you need single value, you can use cmd.ExecuteScalar(); instead of cmd.ExecuteReader();
because ExecuteScalar() will return single value.
First open your sql connection then make object of MySqlCommand like below:
MySqlConnection connection = new MySqlConnection(Konekcija);
connection.Open();
MySqlCommand cmd = new MySqlCommand(komanda, connection);