I am facing problem that. when I insert single quote in text field. on insertion it give exception of incorrect syntax near that particular field. why is it? does single quote has special meaning to sqlserver?
what if user what to enter word like don't , it's, or sometime by mistake enter single quote in start then it give exception. is there any sol to handle this? if single quote has issue with sqlserver.. then how to deal it?
use SqlParameter instead of string concatenation
This kind of expressions is worst thing you can do in your code, because at first you will have problem with data type convertion, and second the doors of Sql Injection is opem for hackers
string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = '" + tbSomeBox.Text+ "'" ;
Instead of that just use this
string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = #param";
SqlCommand someCommand = new SqlCommand(someQuery, conn);
someCommand.AddParams("#param",tbSomeBox.Text);
...
Hope this helps
SQL Server strings are enclosed (typically) in single quotes, so a single quote within a string will result in an error if you don't escape it prior to it being INSERTed.
Single quotes simply need to be doubled up, so the string Will''s World would result in Will's World making it's way into the data.
You will need to escape single quotes in SQL statements.
For example:
'don''t'
In SqlServer, if you want to insert string with quotes, use quotes twice before and after the string. For example you want to insert 'Hello', so insert it like '''Hello''' provided the field you want to insert in has string datatype like varchar etc.
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "(newsequentiali'd())";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name",
SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
Related
I read lots of topics and tried many solutions, but it is not working for me, to insert my data to the database.
public static void Feltoltes(string szo_var, string szotagolva_var)
{
string query = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES ('#szo','#szotagolva')";
command.Parameters.AddWithValue("#szo", szo_var);
command.Parameters.AddWithValue("#szotagolva", szotagolva_var);
System.Windows.Forms.MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
}
conn.Close();
}
}
This is my code. My connection string is the right one. If I insert to the database manually, than I can make SELECTs etc. Only the Insert is not working properly. It don't get any exception, looks like everything works, but nothing changes.
Every thing looks OK except for the insert command text.
Try the following:
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES (#szo,#szotagolva)";
If you use single quates (') inside a SQL command text it will treat what is inside as a literal. And hence it cancels out your parameter designation #
So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.
Consider the following code:
SqlConnection conn = new SqlConnection(#"connection string");
SqlCommand ourCommand = new SqlCommand(String.Format(
#"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE '#FL1'"), conn);
ourCommand.CommandTimeout = 6000;
ourCommand.Parameters.AddWithValue("#FL1", TextBox1.Text);
SqlDataAdapter adapter = new SqlDataAdapter(ourCommand);
DataTable dt = new DataTable();
conn.Open();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
The problem is that datatable is empty - which means the command either was not executed or incorrect query was generated. What am I missing? Connection and query are valid. The command without parameter also works. Database engine is SQL Server 2008 R2
You've put the parameter name in quotes, so it's being treated as a value, not as a parameter. Try this instead:
"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE #FL1"
(I'd actually expect your existing code to throw an exception given that you're supplying more parameters than are in the SQL...)
As noted in comments, you don't need the string.Format either.
Your query is not a well formatted query.
Instead of:
String.Format(
#"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE '#FL1'")
Use:
"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE #FL1"
Note that there is no need for string.Format, nor to enclose the parameter name in '' and since there is nothing to escape in the string, no need for it to be a verbatim string literal (using the #), as Jon commented.
Try changing the line to this (remove the tick marks sorrounding #FL1)
SqlCommand ourCommand=new SqlCommand(
"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE #FL1",conn);
If you are using parameters, you don't need to use single quotes.
Take a look on lesson here.
Well, first, you don't need the string.format or the #'s (you have no escaped chars, your string are on one line, and you aren't using parameterized strings, so there's no reason for either one) Then, you don't need the quotes around #FL1. SqlCommand parses entire string for #'s, not for substrings delimited by quotes. The final code, I believe, should look like this:
SqlCommand ourCommand=new SqlCommand("SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE #FL1",conn);
Everything else I think you can keep the same.
You need to force concatenation with percent % ->
SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE **'%'** + #FL1 + **'%'**
I am trying to insert string as "baby's world" into the column of type varchar through query but shows me error.
Is there anything else i need to put to the query so that it accept that symbol
put a backslash in front of it like so:
"Baby\'s world"
You can find and replace them in your string using the following:
str.Replace('\'', '\\\'')
I'm not 100% sure about this last part, but you need to 'escape' the ' and \ by adding a \ in front of it. So it would seem alright (can't test as i'm not a C# programmer.
Since you are asking about Visual Studio (.NET), you need to use parameterized query. Don't use concatenation when constructing query
private void PrepareExample()
{
string s = Console.ReadLine();
MySqlCommand cmd = new MySqlCommand("INSERT INTO movie(title) VALUES (?title)", myConnection);
cmd.Parameters.AddWithValue( "?title", "baby's world" );
cmd.Prepare();
cmd.ExecuteNonQuery();
}
Or
private void PrepareExample()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO movie(title) VALUES (?title)", myConnection);
// try to input: baby's world. or try: baby"s world. everything are ok :-)
cmd.Parameters.AddWithValue( "?title", Console.ReadLine() );
cmd.Prepare();
cmd.ExecuteNonQuery();
}
Though this is not exactly concatenation, don't use this:
qry = string.Format("INSERT INTO movie(title) VALUES("{0}", Console.ReadLine());
Though if you really found a need to run SQL that way, replace single quote with backslash
qry = string.Format("INSERT INTO movie(title) VALUES("{0}",
Console.ReadLine().Replace("'", "\'");
But do consider using parameterized query instead of concatenation or string.Format, as parameterized query automatically take care of those delimeter nuances.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html
Just use mysql_real_escape_string(). There is no need to do anything else.
For example:
mysql_real_escape_string($user),
mysql_real_escape_string($password));
INSERT INTO table (field) VALUES ('baby's world') will fail because the string is truncated to INSERT INTO table (field) VALUES ('baby' and the rest is seen as invalid code.
There are two ways to stop this, the second being advisable for good practice coding:
INSERT INTO table (field) VALUES ("baby's world")
INSERT INTO table (field) VAUES ('baby\'s world')
well, the question is clear i hope, the code is this:
string sql = "delete from #tabelnaam";
SqlCommand sc = new SqlCommand();
sc.Connection = getConnection();
sc.CommandType = CommandType.Text;
sc.CommandText = sql;
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Input;
param.ParameterName = "#tabelnaam";
param.Value = tableName;
sc.Parameters.Add(param);
OpenConnection(sc);
sc.ExecuteScalar();
tableName is supplied to this function.
I get the exception:
Must declare the table variable #tabelnaam
IIRC, you cant use a substitute the table name for a parameter.
Rather build the SQL string containing the correct table name.
Make to changes
rather than using paramter use this
string sql = string.format( "delete from {0}",tableName);
make use of executenonquery intead of ExecuteScalar
sc.ExecuteNonQuery();
As mentioned by others, you can't parameterise the table name.
However, as you rightly mention in comments on other answers, using simple string manipulation potentialy introduces a SQL injection risk:
If your table name input is fro an untrusted source, such as user input, then using this:
string sql = string.format( "DELETE FROM {0}",tableName);
leaves you open to the table name "myTable; DROP DATABASE MyDb" being inserted, to give you:
DELETE FROM myDb; DROP DATABASE MyDB
The way round this is to delimit the table name doing something such as this:
string sql = string.format("DELETE FROM dbo.[{0}]", tableName);
in combination with checking that the input does not contain either '[' or ']'; you should probably check it also doesn't contain any other characters that can't be used as a table name, such as period and quotes.
I dont think you can parameterize the table name. From what I have read you can do it via Dynamic sql and calling sp_ExecuteSQL.
Your SQL is incorrect, you are deleting from a table variable yet you haven't defined that variable.
Update: as someone has pointed out, you are trying to dynamically build a query string but have inadvertantly used SQL parameters (these do not act as place holders for string literals).
More here:
Parameterise table name in .NET/SQL?
You cannot parameterise the table name, you have to inject it into the command text.
What you can and should do is protect yourself against SQL injection by delimiting the name thus:
public static string Delimit(string name) {
return "[" + name.Replace("]", "]]") + "]";
}
// Construct the command...
sc.CommandType = CommandType.Text;
sc.CommandText = "delete from " + Delimit(tableName);
sc.ExecuteNonQuery();
See here and here for more background info.