I am trying to do an insert query and I keep getting the error:
incorrect syntax near '/'
Here is what I am inserting " /Portals/0/products/HT3-XXX.pdf "
Why can I not insert the '/' ?
Do I need to convert to string? or what?
//Inserts 3DModel
SqlConnection sqlCon2 = new SqlConnection("...");
SqlCommand sqlCmd2 = new SqlCommand();
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", " + textBox4.Text + ") ";
sqlCmd2.Connection = sqlCon2;
sqlCon2.Open();
sqlCmd2.ExecuteNonQuery().ToString();
sqlCon2.Close();
MessageBox.Show("3DModel for " + textBox3.Text + "' Has been Added");
Most likely, it's complaining about the URL you're using as a parameter.
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", " + textBox4.Text + ") ";
sqlCmd2.Connection = sqlCon2;
Parameterize your query and see if it fixes the issue:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES (#TypeId, #ProductId, #Url) ";
sqlCmd2.Parameters.AddWithValue("#TypeId", 3);
sqlCmd2.Parameters.AddWithValue("#ProductId", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#Url", textBox4.Text);
sqlCmd2.Connection = sqlCon2;
Well the problem is because you are missing single quotes around the values in your concatenated query. But your query is prone to SQL Injection. Use SqlParameter.
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', #ProductID, #URL)";
sqlCmd2.Parameters.AddWithValue("#ProductID", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#URL", textBox4.Text);
Consider using using statement with your Connection and Command object to release resources.
You'd have to wrap the value in quotes for SQL to understand that it's a string:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", '" + textBox4.Text + "') ";
However, this code is extremely vulnerable to SQL injection attacks. I'd strongly recommend using a prepared statement instead:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', #productID, #url) ";
sqlCmd2.Parameters.AddWithValue("#productID", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#url", textBox4.Text);
You're currently using the raw content of your text fields. This is a VERY bad idea, because first of all you can't make any characters that might terminate the SQL statement. Second of all, as a result of this, anyone could write a query that drops the entire database.
Now, to answer your question, you're missing quotes around the textboxes.
Currently it could say:
('3', Textbox5ContentHere, Textbox4ContentHere)
When you want
('3', 'Textbox5ContentHere', 'Textbox4ContentHere')
#Edit: Downvoters, please explain.
Related
How do i update the Yes/No Field Select Column using c#?
Here's my table 1 and table 2:
Here is my code:
connection.Open();
OleDbCommand command = new OleDbCommand("update [Table1] set [Select] = #Select, [DocumentName] = #DN where [Table1ID] = " + txtTable1ID.Text + " ", connection);
command.Parameters.AddWithValue("#Select", checkBox1.Checked);
command.Parameters.AddWithValue("#DN", "Form 137");
command.ExecuteNonQuery();
command.Parameters.Clear();
command.Parameters.AddWithValue("#Select", checkBox2.Checked);
command.Parameters.AddWithValue("#Name", "Good Moral");
command.ExecuteNonQuery();
command.Parameters.Clear();
command.Parameters.AddWithValue("#Select", checkBox3.Checked);
command.Parameters.AddWithValue("#Name", "Transcript of Record");
command.ExecuteNonQuery();
connection.Close()
The output with this code:
You miss a comma:
"update [Table1] set [Select] = #Select, [DocumentName] = #DN where [Table1ID] = " + txtTable1ID.Text + ""
Please be aware that your code is vulnerable to SQL Injection attacks.
You should never concatenate SQL like this: [Table1ID] = " + txtTable1ID.Text + " ".
Instead use parametised SQL, like you've done for other bits, such as the "#Select" parameter.
(Sorry, not enough rep to post this as a comment)
when i inserting data into database i need to insert date also but i pass a insert query in this query i inserted data but it took date column by default SQL database date format but i want to display when the user enter data to insert data base that date i want to display my tried query is:
string s = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate) values(" + batchno + ", " + subjectid + " , '" + AudiotoName + "', " + AudioId + ",'" + CBY + "'," + DateTime.Now.ToString() + ")";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but the above query inserting default date in database.i need to insert when i insert data that particular date will be store can any one help me out.
If the date input will always be the current date then you can use the sql method getdate() to fill the value. if it is not, you have to give the date in proper format, that means in "yyyy-MM-dd HH:mm:ss" it is simple to change the format using .ToString() so the query will be :
string s = "insert into BatchPermissons(...,CreatedDate) values(...," + getdate() + ")"; // using standard method date
Or
string s = "insert into BatchPermissons(...,CreatedDate) values(...," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ")"; // using formated date
Special note:
Can we stop opening way to sql injection using text only queries and start writing parameterised queries? So that we can avoid the unwanted FormatingException and also give protection from injection. In this case you can use parameterised queries like the following:
string QuerySql = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate)" +
"values(#batchno,#subjectid,#AudiotoName,#AudioId ,#CBY,#dtime)";
SqlCommand cmd = new SqlCommand(s);
cmd.CommandType = CommandType.Text;
cmd.CommandText = QuerySql;
cmd.Parameters.Add("#batchno", SqlDbType.VarChar).Value = batchno;
cmd.Parameters.Add("#subjectid", SqlDbType.VarChar).Value = subjectid;
cmd.Parameters.Add("#AudiotoName", SqlDbType.VarChar).Value = AudiotoName;
cmd.Parameters.Add("#AudioId", SqlDbType.VarChar).Value = AudioId;
cmd.Parameters.Add("#CBY", SqlDbType.VarChar).Value = CBY;
cmd.Parameters.Add("#dtime", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if you are using the getdate() method then you can avoid the last Parameter from adding value, it will be like the following:
"values(#batchno,#subjectid,#AudiotoName,#AudioId ,#CBY,getdate())"
You can replace the DateTime.Now.ToString() with "getdate()". This will take the date from SQL server. Or add format to the ToString
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
If your Database column type is datetime then try to insert datetime directly like this-
string s = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate) values(" + batchno + ", " + subjectid + " , '" + AudiotoName + "', " + AudioId + ",'" + CBY + "'," + DateTime.Today + ")";
please figure out the error in my code.it show syntax error INSERT INTO statement.
OleDbCommand cmd = new OleDbCommand("INSERT INTO tbbill(invoice,datetime,custm,total,tax,grand)VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",'" + dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "','" + Convert.ToString(txtcn.Text) + "','" + txtttl.Text + "','" + Convert.ToInt32(cmtax.Text) + "','" + txtgrdttl.Text + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
It seems that you've commited all the sins possible in this short fragment.
Something like that is expected:
// Make SQL readable
String sql =
#"INSERT INTO tbbill(
invoice,
[datetime], /* reserved word */
custm,
total,
tax,
grand)
VALUES(
?, ?, ?, ?, ?, ?)"; // Make SQL parametrized
// Put IDisposable into "using"
using (OleDbCommand cmd = new OleDbCommand(sql, con)) {
// Parameterized
cmd.Parameters.Add(txtinvoice.Text);
cmd.Parameters.Add(dateTimePicker1.Value);
cmd.Parameters.Add(txtcn.Text);
cmd.Parameters.Add(txtttl.Text);
cmd.Parameters.Add(cmtax.Text);
cmd.Parameters.Add(txtgrdttl.Text);
cmd.ExecuteNonQuery();
}
// Do not close that's not opened by you (i.e. con)
Apart from your weird INSERT statement, your column name datetime is a reserve word in Access. You should escape it suing [] like below.
INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
Your current query is open to SQL Injection and so as suggested in comment consider using parameterized query instead.
This should work:
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",\"" +
dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "\",\"" +
Convert.ToString(txtcn.Text) + "\",\"" + txtttl.Text + "\",\"" +
Convert.ToInt32(cmtax.Text) + "\",\"" + txtgrdttl.Text + "\")", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
EDIT:
As stated by others, your query is still open to SQL injection. Dmitry's answer will be the safest and efficient option.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Patient_Details (Patient Id,Name,Age,Contact No,Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "',);", con);
object o= sc.ExecuteNonQuery();
MessageBox.Show(o +"Saved data");
con .Close();
}
I see a few things;
Patient Id should be [Patient Id] and Contact No should be [Contact No] since they are more than one word. As a best practice, change their names to one word.
You have extra , at the end of textBox5.Text + "', part.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var con = new SqlConnection(connection))
using(var sc = con.CreateCommand())
{
sc.CommandText = #"insert into Patient_Details ([Patient Id],Name,Age,[Contact No],Address)
VALUES(#id, #name, #age, #no, #address)";
sc.Parameters.AddWithValue("#id", textBox1.Text);
sc.Parameters.AddWithValue("#name", textBox2.Text);
sc.Parameters.AddWithValue("#age", textBox3.Text);
sc.Parameters.AddWithValue("#no", textBox4.Text);
sc.Parameters.AddWithValue("#address", textBox5.Text);
con.Open();
int i = sc.ExecuteNonQuery();
MessageBox.Show(i + " Saved data");
}
By the way, I used AddWithValue in my example since you didn't tell us your column types but you don't. This method might generate surprising results sometimes. Use Add method overloads to specify your parameter type (SqlDbType) and it's size.
Getting an object from ExecuteNonQuery is really strange as well. It will return int as an effected rows count. It will be 1 or 0 in your case.
As a last thing, I strongly suspect your Patient Id, Age and Contact No columns should be some numeric type, not character typed.
fields and table names with spaces must be inside [], also you have 1 extra comma in the end of your query. Try:
SqlCommand sc = new SqlCommand("insert into [Patient_Details] ([Patient Id],Name,Age,[Contact No],Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "');", con);
object o= sc.ExecuteNonQuery();
also consider using parameters, since you are open to sql injection.
I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();