I am inserting data into a .mdf database through a webpage. When I insert words that contain the apostrophe " ' ", it causes an exception. I tried the escape \' but this inserts the whole " \' ". I don't want to insert these directly into the database table through visual studio because I need the Date.Now time/date to be inserted too (through C#).
Please show me how to insert the " ' " and other like characters. Thanks in advance.
That is because you are inserting the data in a way that you should never use. NEVER, NEVER write an SQL command string using string concatenation. Use parameters instead. ie:
Instead of doing this:
var cmd = new SqlCommand("insert into myTable (FirstName, LastName) values ('" +
txtFirstName.Text + "','" +
txtLastName.Text + "')", connection);
Do it like this:
var cmd = new SqlCommand(#"insert into myTable
(FirstName, LastName)
values (#fName, #lName)", connection);
cmd.Parameters.AddWithValue("#fName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#lName", txtLastName.Text);
You can escape it with double apostrophe '', but you shouldn't use it in SqlCommand text. Always add parameters using SqlCommand.Parameters to avoid sql injection possibility.
Related
I am trying to get a carriage return to happen with C# when inserting into an oracle database but I can't seem to get it correct.
I know its CHR(13) but when I run the replace on the string it replaces a specific character that i am using to mark a carriage return but when the insert happens it comes in with "CHR(13)" instead of a carriage return.
This is what I am using:
txt = txt.Replace("|", "' ||CHAR(13)|| '");
I have also tried setting a variable and giving it the calue of char(13) but same result.
INSERT INTO people (id, first_name, last_name, txt) VALUES ('" + id + "', '" + record.first_name + "', '" + record.last_name + "', '" + txt + "')";
Output:
INSERT INTO people (cust_sid, first_name, last_name, notes) VALUES ('10', 'steve', 'man','thisistext ||CHR(13)|| 07, more:more, ||CHR(13)')
Can anyone let me know what I am doing wrong.
Thanks,
Your issue is the last '|' at the end of txt. It's definitely possible to triage this and do what you're trying to do, but as others have said in the comments, please don't.
Consider, what if your variable txt contains the following:
He'll do just fine
How are you going to handle the ' character, and more importantly do you really want to?
Bind variables are like bacon -- they make everything better:
// OracleConnection conn;
int id = 1;
string txt = "this is text|more:more, |";
OracleCommand cmd = new OracleCommand(
"insert into people (id, first_name, last_name, txt) values " +
"(:ID, :FIRST, :LAST, :TXT)", conn);
cmd.Parameters.Add("ID", id);
cmd.Parameters.Add("FIRST", "steve");
cmd.Parameters.Add("LAST", "man");
cmd.Parameters.Add("TXT", txt.Replace("|", Environment.NewLine));
cmd.ExecuteNonQuery();
If you were inserting more than a single record, you'd want to do this a little differently (declare parameters once, execute multiple times with different values), but the same basic concepts would apply.
Is there a way to store TEXT in SQLite database without SQLite trying to parse it?
Ran into a problem where when you store TEXT that is similar to SQLite query, it tries to parse it for some reason.
Query I use to save TEXT: "insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".
Similar text I'm trying to save: "SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".
When i try to save something like that, it says: Error: SQL logic error or missing database near "table":syntax error
Please note that values (name, currentDate, reminder, content) are not hard coded, they are passed as strings. actual code is like below:
SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);
Thanks for any input.
As I suspect, the problem is that you're putting your values directly into the SQL - without even trying to escape them. Don't do that. As well as the problems you're seeing, you've opened yourself up to a SQL injection attack. Use parameterized SQL instead, and specify values for the parameters.
For example:
// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
" (Name, DateCreated, Reminder, Content) values " +
"(#Name, #DateCreated, #Reminder, #Content)");
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.Add("#Name", SQLiteType.Text).Value = noteName;
command.Parameters.Add("#DateCreated", SQLiteType.DateTime).Value = currentDate;
command.Parameters.Add("#Reminder", SQLiteType.Text).Value = reminder;
command.Parameters.Add("#Content", SQLiteType.Text).Value = content;
command.ExecuteNonQuery();
}
I am developing a database application on C# using MS Access for my perfume shop, i have created a table in ms access, named as "MIX", having columns (Brand name,Stock quantity,Retail price,Original price). I want to add their field through C# window form that i have created.
I am trying the following query for inserting my data but all the time i am getting an error "Syntax error in INSERT INTO statement"
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string str = string.Format("Insert into MIX([Brand name],Stock quantity,Retail price,Original price)Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfull");
cmd.Dispose();
}
Four things:
You don't need string.Format when you're just concatenating values
Column names with spaces must be surrounded by square brackets:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")";
You should learn how to use Parameters instead of concatenating SQL:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values (?,?,?,?)");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.Parameters.AddWithValue("brand",textBox1.Text);
... repeat for other values
It appears you're reusing a shared OleDbConnection object. This is not a best practice since connections are pooled in .NET and are cheap to recreate after the first usage, and you don't hae to worry about leaving a connection open throughout the life of your application.
This is a really bad idea since the values are being directly dropped into the query, but the problem you are experiencing is the multi-word column names:
Insert into MIX([Brand name],Stock quantity,Retail price,Original price)
These need to have bracket around them:
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])[
You need to enclose column names that contain spaces insquare brackets []. Also, you need to use parameters instead of concatenating values to the SQL query like that. Google "SQL injection attack" to know the reason why.
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])Values(?,?,?,?)
You replace those ?'s with values this way:
cmd.Parameters.AddWithValue("?", Textbox1.text);
cmd.Parameters.AddWithValue("?", Textbox2.text);
cmd.Parameters.AddWithValue("?", Textbox3.text);
cmd.Parameters.AddWithValue("?", Textbox4.text);
Be aware that the order matters.
I am getting the following error
syntax not correct near item number
but I don't see anything wrong, the values being inserted are from a dataset containing field names in variables from another sql query that is being looped through and then inserted into another table like so....
string strOrderDetails =
"INSERT INTO Orders (Order Number, Item Number, Description, Price) " +
"VALUES ('" + strOrderNo.Replace("'", "''").ToString() + "', '"
+ intItemNo + "', '"
+ strDesc.Replace("'", "''").ToString() + "', '"
+ decPrice + "')";
On execution of the above is where the code falls over and states there's an error near the word item number?
Do I need to do something to the intItemNo as it's an integer?
When a column contains spaces you need to enclose it in square brackets or other delimiter for the choosen database
But said that, please do not use string concatenation to build sql commands, but always a parameterized query.
string strOrderDetails = "INSERT INTO Orders ([Order Number], [Item Number]," +
"Description, Price) VALUES (#ordNum, #temNo, #desc, #price";
using(SqlConnection cn = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand(strOrderDetails, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ordNum",strOrderNo);
cmd.Parameters.AddWithValue("#itemNo",intItemNo);
cmd.Parameters.AddWithValue("#desc",strDesc);
cmd.Parameters.AddWithValue("#price", decPrice);
cmd.ExecuteNonQuery();
}
As you could notice, using parameters remove the need to write code to handle quotes in the input values, but also remove the possibility of Sql Injection attacks
I try to find a way to protect apostrophie in my query string. I have a value in string format that contain apostrophie and it throw me an error when I tried to insert
ex :
Insert into ["excelApp.worksheetsList.ElementAt(0).Name "$"] " + ([col1], [col2])
values values" + " ('" + val1 + "', '" + val2 + "');")
This is an exemple. here val1 contains "hereIsMy'value".
Thanks for helping me
You should use parametrized queries and you don't have to worry about single quotes in query
using(OleDbConnection cn = new OleDbConnection(GetConnectionString()))
{
cn.Open();
string cmdText = "Insert into [" + excelApp.worksheetsList.ElementAt(0).Name + "$] " +
"([col1], [col2]) values (?, ?)";
OleDbCommand cmd = new OleDbCommand(cmdText, cn)
cmd.Parameters.AddWithValue("#p1", val1);
cmd.Parameters.AddWithValue("#p2", val2);
cmd.ExecuteNonQuery();
}
In this example your command text consist of a single string with placeholders for the parameters value. Then a command object is declared to have that string and two parameters are added at its collection of parameters. They are created according to the variable type passed as value. So, if val1 and val2 are strings and a single quote (apostrophe) is present it is automatically formatted for the insert/delete/update or select operation requested
Use parameterized commands and you won't have to worry about such things. You won't have to worry about apostrophes and a bunch of other problems.