I try to write a program for updating data with id. When I write number for id (for example id=7), the program is run and works correctly. But when I write label text and convert to number, the code doesn't update and throws an error.
Here is my code:
private void yadda_saxla_update_Click(object sender, EventArgs e)
{
connect.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
// when i write "id=7" or other number data is update,
// but i want update with label text ( Convert.ToInt32( id_label.Text) )
// and gives error
cmd.Connection = connect;
cmd.ExecuteNonQuery();
connect.Close();
disp_data();
}
And the error is the following:
What can I do? Thanks...
As Others pointed it out in the comments you should not concatenate user inputs because it gives an attacking vector for SQL Injection. (or at least check for harmful inputs)
Otherwise the solution, I think, is that you should remove the ' because at the moment the command currently parsed as a varchar.
This part where id='"+Convert.ToInt32( id_label.Text)+"'" becomes where id='7' instead of where id=7
So unless your ID is stored as a varchar, this line should be changed
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
to
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id="+Convert.ToInt32( id_label.Text);
Related
This is my C# code - I am running the query
INSERT INTO PM
VALUES ('Ali', '6777777', '3', 'Batsman', 'Fine Player', 'njhuh8obj', 'Lahore');
It is running fine in the database, but not this.
protected void btnAdd_Click(object sender, EventArgs e)//button that add players
{
// for picture to be uploaded
string path = "~/Admin/Players" FileUploadPicture.FileName;
FileUploadPicture.SaveAs(Server.MapPath(path));
SqlCommand cmd = new SqlCommand("INSERT INTO PM VALUES ( '" + TxtPlayerName.Text + "','"+TxtPlayerType.Text + "','" + TxtPlayerBasePrice.Text + "','" + TxtPlayerRecord.Text + "',
'" + ddlCat.SelectedItem.Value + "','" + path + "','" + TxtPlayerAddress.Text + "')", con);//Query of my C# page
// open connection with database
con.Open();
// Command for running query
cmd.ExecuteNonQuery();
con.Close();
// message shown after player is added
Response.Write("<script>alert('**Player Added**')</script>");
}
It seems that there is a problem in code of my C# page not in database, but I am not sure about that.
So please help me to solve this out...
It looks like the second column of your database table accepts an integer value but you are passing a string (TxtPlayerType.Text). If you want to insert an entry with only values for select columns you must specify the column names as follows:
INSERT INTO table_name (Column1, Column2, ...) VALUES (Value1, Value2, ...)
When Column Names aren't specified you must pass values in the order they appear in the database table.
Insert statement should follow the below format
Insert into <TableName>(Column1,Column2) Values (Value1,Value2)
It is good practice to define the column names in the statement as it make sure the order of the columns and also in future if new column added or deleted no need to change the code
I'm currently attempting to introduce an update option for my form project. I can successfully save entries to the database, but I want to be able to update these entries if the user gets information in the future that needs to be updated within the database...
Currently my error is, "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'"lossID=8, 25 Oct, 00:00, 25 Oct, 23:59,","" at line 1.
I thought this would be from perhaps the set syntax but I get the same error if I remove it or change anything there. I'm not sure if its because I am using parameters for my insert function, and perhaps just missing something?
My code for this is,
if (start_time.Text == end_time.Text)
{
MessageBox.Show("Please input a different ending time for the loss event");
}
else
{
string constring = "datasource=localhost;port=3306;username=root;password=1234; ";
string query = "update lossdatabase.losstable set (lossID= '" + this.textBox1.Text + "', #Start, #Start_Time, #End, #End_Time, #Equipment, #Event, #Responsibility, #Cause, #Reason, Capacity_Loss='" + capacity + "', Planned= '" + Planned + "', Scheduled='" + Scheduled + "', Prepared='" + Prepared + "', #Primary_Rate, #Primary_Volume, #Primary_Percentage, #Secondary_Rate, #Secondary_Volume, #Secondary_Percentage, #Comment) where lossID= '" + this.textBox1.Text + "' ;";
//Defines the connection string to allow data to be deposited into the database, along with defining the variables and columns for the data to be added to
MySqlConnection conLossDB = new MySqlConnection(constring);
MySqlCommand cmdLossDB = new MySqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("#Start", start_date.Text);
cmdLossDB.Parameters.AddWithValue("#Start_Time", start_time.Text);
cmdLossDB.Parameters.AddWithValue("#End", end_date.Text);
cmdLossDB.Parameters.AddWithValue("#End_Time", end_time.Text);
cmdLossDB.Parameters.AddWithValue("#Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Event", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Responsibility", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("#Cause", richTextBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Reason", richTextBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Rate", Rate_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Volume", Volume_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Percentage", Percentage_box.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Rate", Rate_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Volume", Volume_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Percentage", Percentage_2.Text);
cmdLossDB.Parameters.AddWithValue("#Comment", richTextBox3.Text);
//Defines which boxes to read in order to input the text from the defined boxes into the corresponding columns
MySqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("The loss entry has successfully been updated");
//Opens the database and carries out the defined command outlined in the code above
this.Close();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay
I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.
i have connected my database with my windows form, i put the values of my database table column at a listbox, and i want to do the following: when i select an item from the listbox, another column of the table will appear in another textbox. To be more specific, drink names appear at the listbox( espresso,water etc) and i want their price to appear at a textbox , when they are selected from the listbox. I used the following code to do that:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=root;";
string Query = "select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; ";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string dprice = myReader.GetString("drink_price");
pricebox.Text = dprice;
}
}
After i debug my project, it successfully shows the items at the listbox, but when i select them i get this error "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 '='Espresso'' at line 1"
The code from database is the following:
DROP TABLE IF EXISTS `apps`.`drinks`;
CREATE TABLE `apps`.`drinks` (
`drink_name` varchar(45) NOT NULL,
`drink_price` varchar(45) NOT NULL,
PRIMARY KEY (`drink_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into apps.drinks (drink_name,drink_price)
values ('Nes','1'),('Espresso','1'), (...)
Please can you help me??
The query where it fails on is:
"select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; "
there you have is = which is incorrect, remove is so the query looks like:
"select * from apps.drinks where drink_name ='" + listBox1.Text + "'; "
Also take the comment of w0lf seriously and use prepared statements to prevent SQL injection.