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 + **'%'**
Related
I got value from SQL Server using this C# code:
SqlDataReader reader = new SqlCommand("select Top 1 Client From _ClientName group by Client order by count(*) desc", sqlCon.ShardDB).ExecuteReader();
How can I use this value again to insert it into another table?
Just use name of the column begin returned from the database i.e "Client" here. If it is a string, you can use .ToString(). If it is another type, you need to convert it using System.Convert
string Value = reader["Client"].ToString();
First, for readability sake, try separating your code into separate lines, like so:
SQLReader reader;
SQLCommand SQLCmd = new SQLCommand();
SQLCmd.CommandText = "select Top 1 Client From _ClientName group by Client order by count(*) desc";
SQLCmd.Connection = sqlCon.SharedDB;
reader.Execute(SQLCmd);
If I understood your comment to Sajeetharan's previous answer, you want to know how to advance to the next result if your query returns more than one. Have you tried SQLReader.Read()?
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
I just want to know why we use "#" while inserting or updating or deleting data in sql table, as I used #name like below.
cmd.Parameters.Add(new SqlParameter("#fname", txtfname.Text));
See: SqlParameter.ParameterName Property - MSDN
The ParameterName is specified in the form #paramname. You must
set ParameterName before executing a SqlCommand that relies on
parameters.
# is used by the SqlCommand so that the value of the parameter can be differentiatd in the Command Text
SqlCommand cmd = new SqlCommand("Select * from yourTable where ID = #ID", conn);
^^^^^^^
//This identifies the parameter
If # is not provided with the parameter name then it is added. Look at the following source code, (taken from here)
internal string ParameterNameFixed {
get {
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('#' != parameterName[0])) {
parameterName = "#" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
EDIT:
If you don't use # sign with the parameter then consider the following case.
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from yourTable WHERE ID = ID";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("ID", 1);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
The above will fetch all the records, since this will translate into SELECT * from yourTable WHERE 1=1, If you use # above for the parameter ID, you will get only the records against ID =1
OK, no offense to the posters before me but I will try to explain it to you as simple as possible, so even a 7 year old understands it. :)
From my experience '#' in .SQL is used when you are "just not making it clear what exact data type or exact name will be used". "Later" you are pointing out what the exact value of '#' is.
Like, say, someone has developed some huge .SQL query which contains, say, the name of every person who has received it.
SELECT column_name,column_name FROM table_name WHERE column_name = #YOURNAME;
#YOURNAME = 'John Doe';
So, in this case, it's easier for everyone to just write their name at #YOURNAME and it will automatically convert the query to (upon launch):
SELECT column_name,column_name FROM table_name WHERE column_name = 'John Doe';
P.S: I am sorry for my syntax errors and incorrect terminology but I am sure you should have understood it by now. :)
Variables and parameters in SQL Server are preceded by the # character.
Example:
create procedure Something
#Id int,
#Name varchar(100)
as
...
When you create parameter objects in the C# code to communicate with the database, you also specify parameter names with the # character.
(There is an undocumented feature in the SqlParameter object, which adds the # to the parameter name if you don't specify it.)
I have some questions about how to prevent sql injectiion with the help of parameterised queries
sqlQuery="SELECT * FROM usersTbl WHERE username=#uname AND password=#passwd";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
SqlParameter[] par = new MySqlParameter[2];
par[0] = new SqlParameter("#uname ", SqlDbType.VarChar,25);
par[1] = new SqlParameter("#passwd", SqlDbType.VarChar, 45);
And then I attach them to the SqlCommand and ExecuteScalar it.
For example the client insert the string ;DROP -- in the password variable, will the parameterised query prevent the DROP query to be executed ?
Thank you
Of course, when the client pass ';DROP -- value in the password field, this will be parsed into
SELECT *
FROM usersTbl
WHERE username=#uname AND password=''';DROP --'
The command object will automatically escapes any single quotes found on the value.
UPDATE 1
As, I already told you, it won't. Because the quotes will be escaped by doubling the quotes. Example,
string pass_val = "'; DROP usersTbl;--";
when you passed that into command and its value is parameterized, this will become
SELECT * FROM usersTbl WHERE ... AND password='''; DROP usersTbl;--'
and NOT
SELECT * FROM usersTbl WHERE ... AND password=''; DROP usersTbl;--
Yes, the parameterized query will correctly escape any characters that would allow this to happen.
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')
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())
{
}
}
}