trouble updating to mysql inside reader loop - c#

I am looping through these mysql rows and processing data. But, in part of the processing I am also wanting to update into the same mysql table.
This is not working for me.
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
CODE
string connString = "Server=localhost;Port=3306;Database=communications;Uid=myuser;password=mypass;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(reader["account"].ToString());
SendFax(reader["filepath"].ToString(), reader["filepath"].ToString(), reader["id"].ToString(), reader["fax"].ToString());
string id = reader["id"].ToString();
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
}
}

I think that last command.ExecuteReader() tries to open one more reader, but it is not possible to do with one connection. Close first open reader firstly, then modify this table; or try to use command.ExecuteNonQuery() method.

Related

Populating textbox from after selecting value from comboBox

I am trying to populate my textbox after selecting a value from my comboBox.
My code is running fine, I don't have any errors when I run it but when I select a value from my comboBox, it's not populating my textbox. See my code below.
private OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
}
private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
command.CommandText = query;
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Two immediate issues that I see:
You are populating the CommandText property of the OleDbCommand object after issuing the ExecuteReader method, meaning there is no SQL statement being evaluated.
The SQL statement should be populated before the ExecuteReader method is issued, i.e.:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
The where clause of your SQL statement assumes that patientNo contains string data, which could be incorrect given the name of this field.
Just found out the issue. Had the wrong value to compare my Lastname.Text with and fixed the code's arrangement. Thanks for all your help everyone.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();

How to update records in SQL Server database through asp.net?

I'm writing this code in asp.net but still it's not updating record in a SQL Server database:
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
Proper way to use ado.net:
var newId = count + 1;
var roomType = typeRadioButtonList1.SelectedItem.ToString();
using (var connection = new SqlConnection("your db connection string here"))
{
var query = "UPDATE [roomdetail] SET [rid] = #rid WHERE [rid] = 0 AND roomtype = #roomType";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#rid", newId);
command.Parameters.AddWithValue("#roomType", roomType);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
}
You are Missing ExecuteNonQuery Method Write Below code
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
cmd3.executeNonQuery();
Assuming the connection is already opened, in your while loop you are missing the following statement:
cmd3.ExecuteNonQuery();
You have to execute the command in order for the database to be updated.

two queries in same method

I am trying to execute two queries in the same method but it gives me this exception. I can get red of this exception by declaring new command but is there any way to use the same command?
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();
You need to close your OleDbDataReader object when you are finished with it:
// previous code omitted for brevity
//
while (reader.Read())
{
id = reader[0].ToString();
}
// need to close reader
//
reader.Close();
// run your other query (omitted for brevity)
And as the comment on your question states, the way you construct your query is extremely vulnerable to a SQL inject attack. Parameterize your query the proper way.
As per Dmitry's comment, I completely agree. Wrap your OleDbDataReader object in a using block to call OleDbDataReader.Dispose() upon completion of the block:
using (OleDbDataReader reader = command1.ExecuteReader())
{
// ...
}
You need to close the reader after first execution,so code will be like this
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
////////code for closing the reader/////////////
reader.Close();
///////////////
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();

how to solve this SQL and foreign language issue?

I wrote this procedure in a site. it take a string as input parameter(user name) and looks into the related table to find out it's record and return the "ID" field as output of procedure.
this work fine but there's one (major) problem, which is when it take a input in other English language, it can't find the target record and return "-1" as output.
The visitors use Persian language and i observed it in my SQLserver. The collation is "Persian_100_CI_AI" and my string fields are "nvarchar".
what should i do to solve this problem?
i'm using SQL-Server 2008.
thanks a lot
protected int GetThisUserID(string uname)
{
string returnvalue = "";
int returnintegervalue = -1;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OldEagleConnectionString"].ToString());
try
{
//SqlCommand command = new SqlCommand("SELECT [ID] FROM [Customers] WHERE ([Uname] = '" + User.Identity.Name.ToString() + "'", connection);
//SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = '" + User.Identity.Name.ToString() + "')", connection);
SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = '" + uname + "')", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
returnvalue = reader["ID"].ToString();
returnintegervalue = Int32.Parse(returnvalue);
}
}
}
catch (SqlException ex)
{
Response.Write(ex.Message.ToString());
returnvalue = ex.Message.ToString();
}
finally
{
connection.Close();
SqlConnection.ClearPool(connection);
}
return returnintegervalue;
}
I hate to answer my own question but here it is:
have to add a N in select command, just like this:
SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = N'" + uname + "')", connection);
problem solved!
Without the N, the string is taken to be a varchar, and the conversion loses characters outside of that supported by the varchar encoding of the database.

how to fill textbox from dataset?

i run this and i want to fill textbox txtFname with data - but it dont do nothing
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
txtFname.Text = dsView.Tables[0].Rows[3][0].ToString();
txtFname.DataBind();
Conn.Close();
}
how to do it ?
thank's in advance
using (Conn = new SqlConnection(Conect)) {
try {
// Attempt to open data connection
Conn.Open();
// Compose SQL query
string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim());
using(SqlCommand command = new SqlCommand(SQL,Conn)) {
// Execute query and retrieve buffered results, then close connection when reader
// is closed
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) {
// Assign txtFname value to search value and clear value if no results returned
txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty;
reader.Close();
}
}
}
finally {
// Regardless of whether a SQL error occurred, ensure that the data connection closes
if (Conn.State != ConnectionState.Closed) {
Conn.Close();
}
}
}
However, I would advise that you
update your SQL query to return the
actual column names instead of *
replace reader[0].ToString() with
reader["FirstName"].ToString()
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
SqlCommand command= new SqlCommand(SQL,Conn);
SqlDataReader reader = command.ExecuteReader()
reader.Read();
//Call Read to move to next record returned by SQL
//OR call --While(reader.Read())
txtFname.Text = reader[0].ToString();
reader.Close();
Conn.Close();
}
Edit: I just noticed 'dataSet' not database, anyway you are reading third row, is your query returns more than one row?

Categories