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.
Related
Hey My Insert Statement isn't Working I used the same code for inserting other panel data to excel sheet it's working perfectly there but when I'm trying to insert data in other sheet using second panel it's throwing exception "Insert INTO Statement is not valid" I check every single thing in this i can't find any mistake in it. I'm using OleDb For Insertion.
Here is the same code I've been using for first panel insertion.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
String filename1 = #"E:DB\TestDB.xlsx";
String connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(connection);
con.Open();
int id = 4;
string user = txtMUserName.Text.ToString();
string pass = txtMPassword.Text.ToString();
string role = txtMRole.Text.ToString();
DateTime date = DateTime.Now;
string Date = date.ToString("dd/MM/yyyy");
//string Time = date.ToLongTimeString();
string Time = "3:00 AM";
String Command = "Insert into [Test$] (UserID, UserName, Password, Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
OleDbCommand cmd = new OleDbCommand(Command, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Seems like you are using a reserved name for column Password. you need to escape it with []:
string Command = "Insert into [Test$] (UserID, UserName, [Password], Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
Here is the code:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/charlyn_dale/Documents/Visual Studio 2010/Projects/LMS/WindowsFormsApplication2/Accounts.accdb;Persist Security Info=False");
OleDbCommand conn = new OleDbCommand(str);
con.Open();
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, con);
conn.ExecuteNonQuery();
MessageBox.Show("Registration Success!");
con.Close();
and the error is:
Connection property has not been initialized
There are 3 main issues in your Access DB connection:
OleDbConnection connection string property has not initialized when opening OLE DB connection (note that con is different from conn in this context).
The connection string wrongly assigned to variable conn which declared as OleDbCommand, use OleDbConnection instead.
The connection string data source path seems invalid by using slash sign for directory separator (assuming target file exists in Windows folder), use backslash escape sequence (\\) or single backslash with literal string instead (e.g. #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......").
Hence, the correct connection sequence should be like this:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\charlyn_dale\\Documents\\Visual Studio 2010\\Projects\\LMS\\WindowsFormsApplication2\\Accounts.accdb;Persist Security Info=False");
using (OleDbConnection conn = new OleDbConnection(str))
{
conn.Open();
// security tips: better use parameter names to prevent SQL injection on queries
// and put value checking method for all textbox values (sanitize input)
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values ('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
conn.ExecuteNonQuery();
}
... // other stuff
conn.Close();
}
NB: using statements added due to OLE DB connection should be disposed immediately after usage to free up resources.
Similar issues:
get an error as ExecuteNonQuery:Connection property has not been initialized
ExecuteNonQuery: Connection property has not been initialized (access database)
ExecuteNonQuery: Connection property has not been initialized
Am not able to fix the error below:
`"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.
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");
}
}
}
I've managed to run this query using wamp.
INSERT INTO guest (guestno,familyname)
VALUES(NULL,'Damn');
INSERT INTO reservation (reservationno, guestno)
VALUES(NUll,LAST_INSERT_ID())
However If I separately execute these 2 insert statements I will have a foreign key constraint.
I think the both of them need to be executed at the same time.
My questions are:
How to incorporate this into my c# winform code?
Is it possible to have 2 insert statements on one button?
When the user presses "add reservation" I would like the two MySQl query's to be executed.
Here's my insert statement:
private void button7_Click(object sender, EventArgs e)
{
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "<insert statement>";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
}
UPDATED VERSION (DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
Form3 f3 = new Form3();
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "insert into guest (guestno, familyname) values (null, '" + textBox6.Text + "'); insert into reservation (reservationno, guestno) values (null, LAST_INSERT_ID())";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
MessageBox.Show("Added Guest Reservation Successfully");
f3.guestList();
f3.reservationList();
Updated No.3 (STILL DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
dbcmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
dbcmd.CommandType = CommandType.StoredProcedure;
dbcmd.Parameters.AddWithValue("familyName", "foo");
dbcmd.ExecuteNonQuery();
enter code here
You can't execute more than one statement on a given MySqlCommand.
Your best bet all around (maintainability, performance, readability) is to:
create a MySQL stored procedure for your 2 SQL statements.
call your stored proc using ExecuteNonQuery().
DELIMITER //
CREATE PROCEDURE CreateGuestAndReservation
(
IN familyName VARCHAR(255)
)
BEGIN
insert into guest (guestno, familyname)
values (null, familyName);
insert into reservation (reservationno, guestno)
values (null, LAST_INSERT_ID());
END//
DELIMITER ;
Call it from your WinForms code like this:
dbcon.Open();
cmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("?familyName", "foo");
cmd.Parameters.Add("?familyName", MySqlDbType.VarChar,255).Value = "foo";
cmd.ExecuteNonQuery();
The code below should work but I suspect you may have already tried it given that you are asking for help?
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,'Damn'); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
If you need parameters, try this:
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,?familyName); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
...
dbcmd.Parameters.Add("#familyName", MySqlDbType.VarChar, 80).Value = _familyName;
EDIT: You may need to run 2 insert commands. See here.
I would suggest having a way to get ids other than relying on automatic id generation like autoincrements of mysql and sql server, which are very limiting. If you use a HILO id generator you first obtain id, and then execute a couple of inserts in a single transaction no problem, since you know your parent id beforehand.
It will not solve your immediate problem, but it will help tremendeously in future with your application, especially if storing parent-children like data is going to occur often.
Try this, it will work:
private void button56_Click(object sender, EventArgs e) {
con.Open();
SqlCommand cmd = new SqlCommand("insert into stholidays values('" + dateTimePicker12.Text + "','" + dateTimePicker20.Text + "','" + dateTimePicker13.Text + "','" + mbk + "','" + dateTimePicker14.Text + "','" + dateTimePicker15.Text + "','" + lt + "','" + dateTimePicker16.Text + "','" + dateTimePicker17.Text + "','" + ebk + "','" + dateTimePicker18.Text + "','" + dateTimePicker19.Text + "','" + textBox105.Text + "','" + textBox106.Text + "','" + textBox107.Text + "','" + dd + "','" + textBox104.Text + "')", con);
SqlCommand cmd1 = new SqlCommand("insert into holidays values('" + dd + "','" + ms + "','" + day + "','" + textBox104.Text + "')", con);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
}