Here is the problem. I am trying to execute a query and its throwing and exception at connection.Open. Strangely, on the same application I am executing a "Select" query and it works fine. But when I execute the "Update" query it throws this Unable to connect to any of the specified MySQL hosts error. Been stuck on this forever. Can someone spot where I am going wrong.
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
"Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";
command.ExecuteNonQuery();
MessageBox.Show("Settings updated");
}
I'm going to recommend you do the following:
private void button1_Click(object sender, EventArgs e)
{
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connString))
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
"Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";
command.ExecuteNonQuery();
MessageBox.Show("Settings updated");
}
}
I understand that you are thinking to yourself, that you should maintain your connection for ease of use and blah blah, but in my experience, it's wasted effort. What ends up happening its lots of trouble that you don't want or need. You end up not realizing that you have a connection open somewhere else and you spend hours troubleshooting things that you shouldn't. Open your connection, close it when you are done.
If you want to have a single connection object, that's fine, but use the using pattern so that it is disposed of every time, and always start fresh with your connections.
NOTE: replace my connection with yoru MySqlConnection object!
As Mike said, you always better use "using" block as it disposes any connection once it goes out of using block. I used two using blocks below one for connection and other for command object.
Try this
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connString))
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
string queryString = "update Admin_Settings set Difficulty='" +
comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," +
"NoOfChoices='" + comboBox5.Text + "'," + "Subject='" + comboBox8.Text +
"'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled +
"," + "TimerType='" + comboBox1.Text + "'";
using (SqlCommand command = new SqlCommand(queryString, connection))
{
//update the settings to the database table
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
MessageBox.Show("Settings updated");
}
}
}
Related
This question already has answers here:
how to get the last record number after inserting record to database in access
(6 answers)
Closed 1 year ago.
Am working with Access as Database in C# (Visual Studio 15). I want to save form entries (add record) into the Access Database and would want the corresponding ID of the record to show in MsgBox upon a successful saving. I have tried the following:
private void Form21_Load(object sender, EventArgs e)
{
try
{
connection.Open();
checkConnection.Text = "Server Connection, Successful";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, Server not connected " + ex);
}
}
private void Button6_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Students_File ([YourNames],[Nationality],[StateOfOrigin],[PlaceOfBirth],[DoB],[HomeAddress],[LastSchools1],[LastClass1],[LastSchools2],[LastClass2],[LastSchools3],[LastClass3],[AdmClass],[CurrentClass],[Guidian],[GuardianContact],[UserName],[PassWord],[Gender],[RegistrationDate]) values('" + YourNames.Text + "','" + Nationality.Text + "','" + StateOfOrigin.Text + "','" + PlaceOfBirth.Text + "','" + DoB.Text + "','" + HomeAddress.Text + "','" + LastSchools1.Text + "','" + LastClass1.Text + "','" + LastSchools2.Text + "','" + LastClass2.Text + "','" + LastSchools3.Text + "','" + LastClass3.Text + "','" + AdmClass.Text + "','" + CurrentClass.Text + "','" + Guidian.Text + "','" + GuardianContact.Text + "','" + UserName.Text + "','" + PassWord.Text + "','" + Gender.Text + "','" + RegistrationDate.Text + "')";
command.ExecuteNonQuery();
//MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
command.CommandText = "Select * from Students_File where UserName='" + UserName.Text + "' and PassWord='" + PassWord.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
this.Close();
}
else if (count > 1)
{
MessageBox.Show("Sorry, the chosen username or password is currently existing or picked by another user. Consequently, your registration was not successful. Do please, decide another but a unique one. Thank you");
}
connection.Close();
}
You can do it this way:
using (OleDbCommand Command = new OleDbCommand("", conn))
{
Command.CommandText = "Your big ugly mess - need to change this to parmaters!)";
Command.Connection.Open();
Command.ExecuteNonQuery();
Command.CommandText = "Select ##Identity";
var intLastID = Command.ExecuteScalar;
MsgBox("Last id into database = " + intLastID);
}
As noted, you do want to change that insert command - it too long, too difficult to maintain, and subject to mistakes in code and even sql injection.
But, for now, you can use the above approach to get/pick up the last ID insert.
In solution to my inquiry, i have the following code (From Kevin):
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#CategoryName", OleDbType.Integer);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
Now, my challenge is how do i get the ID to appear in messagebox after a successful record creation. Please consider my earliest code in this post in connection with this.
My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.
try
{
SqlConnection.Open();
string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";
try
{
SqlCommand.Connection = SqlConnection;
SqlCommand.CommandText = sqlZapytanie;
SqlCommand.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
}
Perhaps the error to be returned is not type SqlException but type Exception.
i'm using MySQL Database with my c# application , and the database in server in locally.
In Each function in the application (Button click, etc.) i open the connection and in the end i close it, like this:
private void btn_addAccount_Click(object sender, EventArgs e)
{
try
{
**objConn.Open();**
//
MySqlCommand cmd;
if(from == "bill_Details")
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "',"+ Bill_Details.cus_Sup +")", objConn);
else
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "'," + Suppliers.cus_Sup + ")", objConn);
cmd.ExecuteNonQuery();
**objConn.Close();**
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I felt in this way that the application need more time to open and close the connection !
is't right like that or i have to open the connection in the starting of application and close it when it close !?
I'm getting this error code: "unclosed quotation mark after the character string" on the line: cmd.ExecuteNonQuery();
I've looked, but I don't know what's wrong. I also tried just putting two of the textboxe, but I can't seem to debug it. Please advise. Thanks!
Here's the code:
namespace Inventory
{
public partial class NewData : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection("Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234");
protected void Page_Load(object sender, EventArgs e)
{
}//end page load
protected void addButton_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" + Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
cmd.ExecuteNonQuery();
cn.Close();
status.Visible = true;
status.Text = "Added succesffully!";
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//end add button
protected void clearButton_Click1(object sender, EventArgs e)
{
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//clear button
}//end
}//end
As far as I can see, you have unnecessary single quote at the end of your query.
Notestb.Text + "')'
^^ here
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var cn = new SqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
// Set your CommandText property with your parameter definitions
// Add your parameters and their values with Add method
// Open your connection
// Execute your query.
}
Your command ends with an extra single quote. It should be:
cmd.CommandText = "INSERT INTO Inventory values('" +
Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text +
"','" + Serialtb.Text + "','" + Assignedtb.Text + "','" +
Locationtb.Text + "','" + Notestb.Text + "')";
I think the problem is
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" +
Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
there you single comma ' after the right bracket ).
Should have been:
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','"
+ Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text
+ "')";
I want to change the value of a column in a SQL Server table from filtered by 2 others columns. But it returns error: Incorrect syntax ",". Here is code:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "user_item");
connection.Close();
MessageBox.Show("Item Amount Changed");
}
Thank you!
You are missing a space before WHERE.
And you have a comma where you want to use AND.
Change like this:
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "' WHERE char_id='" +
textBox1.Text + "' AND item_type='" + textBox2.Text + "' ";
The sql where conditions will be either combined by using AND or OR so you need to replace the comma ( textBox1.Text + "' ,item_type='" +) with the wanted expression.
Also it would be much better with regard to sql injection, to use command parameters for the values beeing compared and updated.
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "' WHERE char_id='" + textBox1.Text + "' AND item_type='" + textBox2.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "user_item");
connection.Close();
MessageBox.Show("Item Amount Changed");
}
Two mistakes - Space before WHERE and missing AND in WHERE clause
Raj
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
here
,item_type= ',' should be "and" or "or"
You need to add a space between ' and where. Also, you are doing an update and populating a data set? Are you just looking to do an update or are you trying to get data as well?
You should look to use string.Format() here to make it more readable. Also, consider parameterized query as you are leaving yourself open to sql injections. Better still, ditch the dynamic sql and replace with a stored procedure.
Tutorial on String.Format()
If you're not using the dataset, then use ExecuteNonQuery()
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" +
"Initial Catalog=" + "lin2world" + ";" + "User ID=" +
System.IO.File.ReadAllText("User.ini") + ";" + "Password=" +
System.IO.File.ReadAllText("Password.ini");
string sql = string.Format("UPDATE user_item SET amount='{0}' WHERE char_id='{1}' AND item_type='{2}'",
textBox3.Text, textBox1.Text, textBox2.Text);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
MessageBox.Show("Item Amount Changed");
}
I highly recommend you not to use this format:
sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
instead, you should use:
sql = String.format("UPDATE user_item SET amount=%d WHERE char_id=\'%s\' and item_type=\'%s\'",textBox3.Text,textBox1.Text,textBox2.Text);
This form is much more clear to avoid errors.