Say I have a basic query, something like this:
SELECT holiday_name
FROM holiday
WHERE holiday_name LIKE %Hallow%
This executes fine in my sql query pane and returns 'Halloween'. My problem occurs when I try to use parameters with with the wildcard '%' characters in my code.
SqlConnection Connection = null;
SqlCommand Command = null;
string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString;
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE %#name%";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text));
var results = Command.ExecuteScalar();
}
catch (Exception ex)
{
//error stuff here
}
finally
{
Command.Dispose();
Connection.Close();
}
This throws an incorrect syntax error. I've tried moving the '%' to my parameter like so
Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));
but then I receive an error saying I haven't declared the scalar variable '#name'. So, how do you properly format wildcard characters to be included with query parameters? Any help is appreciated!
First off, your SqlParameter name is #name not name.
Second, I would move your wildcards.
So it would look like this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name;"
Connection = new SqlConnection(ConnectionString);
try
{
var escapedForLike = HolidatyTextBox.Text; // see note below how to construct
string searchTerm = string.Format("%{0}%", escapedForLike);
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("#name", searchTerm));
var results = Command.ExecuteScalar();
}
Note that LIKE requires special care when passing parameters and you need to escape some characters Escaping special characters in a SQL LIKE statement using sql parameters.
whatever you do don't do this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
as that will open you up to sql injection, instead do this:
Command.Parameters.Add(new SqlParameter("#name", "%" + HolidayTextBox.Text + "%"));
you may like to know about Command.Parameters.AddWithValue, e.g:
Command.Parameters.AddWithValue("#name", "%" + HolidayTextBox.Text + "%");
The %s should be part of the search string, not the query.
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
string name = "%" + HolidayTextBox.Text + "%";
Command.Parameters.Add(new SqlParameter("#name", name));
Related
I have a winform and a textbox which will pass the value to a prepared statement like this
searchKey = "member_chinese_name";
field_name = "member_chinese_name";
daoQuery = "SELECT * FROM member where member_chinese_name like #" + searchKey;
sqlCmd = new MySqlCommand(daoQuery, databaseConnection);
MessageBox.Show(field_name + " " + field_value1);
sqlCmd.Parameters.Add(new MySqlParameter("#"+field_name , field_value1 + "%"));
sqlCmd.CommandTimeout = 60;
sqlCmd.ExecuteNonQuery();
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
the whole query is (select * from member where member_chinese_name like 中文字%;)
the query has no result run in my winform, but i run the sql in phpmyadmin (select * from member where member_chinese_name like '中文字%') is valid
Anyone know what is the problem?
Remarks (search english is ok)
The problem might be the parameter you are sending for the search. It should be #searchKey instead of #" + searchKey; and you can also choose sqlCmd.Parameters.AddWithValue instead of sqlCmd.Parameters.Add(new MySqlParameter thus code would look like
searchKey = "member_chinese_name";
field_name = "member_chinese_name";
daoQuery = "SELECT * FROM member where member_chinese_name like #sKey";
sqlCmd = new MySqlCommand(daoQuery, databaseConnection);
MessageBox.Show(field_name + " " + field_value1);
//not sure which variable stores 中文字
sqlCmd.Parameters.AddWithValue("#sKey", field_value1+"%");
I am connecting to a compact SQL database server through a WCF service and keep getting the following except on the Command.ExecuteNonQuery(). I have tried fixing this but just don't know what's wrong.
The exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred
in System.Data.SqlServerCe.dll but was not handled in user code
The code:
//The connectionString can be found in the properties table of the database
string connString = "Data Source=C:\\Users\\User\\documents\\visual studio 2012\\Projects\\ADO_LINQ\\ADO_LINQ\\App_Data\\MyDatabase.sdf;Persist Security Info = False";
SqlCeConnection myConnection = new SqlCeConnection(connString);
myConnection.Open();
// Create the query
string myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + "," +
firstName + ", " +
lastName + ", " +
phoneNumber + ", " +
address + ", " +
dateOfBirth + ");";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
//Run the command
myCommand.ExecuteNonQuery();
//Close the connection
myConnection.Close();
You are missing Single quotes around your string data types, Assuming only registrationID is Integer data type and all other columns are String data type , your query should look something like ......
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + ", '"+ firstName +"' , '"+lastName+"' , '"+phoneNumber+ "', '"+ address +"', '"+dateOfBirth+"' );";
A better and safer option would be to use Parametrised query. Something like this.....
String connString = #"Data Source=C:\Users\User\documents\visual studio 2012\Projects\ADO_LINQ\ADO_LINQ\App_Data\MyDatabase.sdf;Persist Security Info = False";
using(SqlCeConnection myConnection = new SqlCeConnection(connString))
{
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (#registrationID , #firstName , #lastName , #phoneNumber, #address , #dateOfBirth );";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
// Add parameters
myCommand.Parameters.AddWithValue("#registrationID" ,registrationID);
myCommand.Parameters.AddWithValue("#firstName" , firstName);
myCommand.Parameters.AddWithValue("#lastName" , lastName);
myCommand.Parameters.AddWithValue("#phoneNumber" , phoneNumber);
myCommand.Parameters.AddWithValue("#address" , address);
myCommand.Parameters.AddWithValue("#dateOfBirth" , dateOfBirth);
//Open Connection
myConnection.Open();
//Run the command
myCommand.ExecuteNonQuery();
}
I am trying to pass parameters from my program to Stored Procedure in EXEC format.Following is my code
public void button1_Click(object sender, EventArgs e)
{
frm = new FrmLogin();
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string user = username.Text;
string pass = password.Text;
string query = "EXEC dbo.checkuser"' + username.Text'" + " " + "'password.Text'"";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
// Retrieve the return value
string result = query.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
What should I write in string query=" "?,I am trying to pass username and password as parameters to the stored procedure and once the query executes and returns the result ,I will store it in another variable named result.Am I doing it the right way? I am new to C#
Please suggest,
Thanks
Building command text with dynamically inserted segments from user input is very dangerous, and leaves you open to SQL Injection.
Below is a slight variation which parameterizes those strings. This approach is much safer.
string query = "dbo.checkuser";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
Note: This updated version sets up the command as a stored procedure, instead of plain text.
try this
OleDbCommand cmd = new OleDbCommand("StoredPorcedureName",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameter.AddWithValue("#user", username.Text);
cmd.Parameter.AddWithValue("#pwd", password.Text);
cmd.ExecuteNonQuery();
That looks Okay at a glance except for your query string. Change to:
string query = "EXEC dbo.checkuser '" + username.Text "', '" + password.Text + "'";
might work better.
Edit
Yes, as per comments about SQL injection, Troy's answer is significantly better.
Just for completeness that can be possibly used in other situations, you can avoid SQL injection using this method by trying something like:
string query = "EXEC dbo.checkuser '" + username.Text.Replace("'", "''") "', '" + password.Text.Replace("'", "''") + "'";
I use this code in my project (SQL COMPACT):
"select Name
from Drug
where Name
like '" + Dname + "%'
limit 10"
Dname is a string value. The result is this error:
There was an error parsing the query.
[ Token line number = 1,Token line offset = 44,Token in error = LIMIT ]
Why is this happening and how can I fix it?
i think what you want is
"select TOP (10)
from Drug
where Name
like '" + Dname + "%' "
you should also try using parametrized queries:
string qry = "select TOP(10) from Drugs where name like #dname";
SqlCommand oCmd = new SqlCommand(qry, ConnectionString);
oCmd.Parameters.AddWithValue("#dname", dname + '%');
Never use string concatenations to build SQL queries. Always use parametrized queries:
string connectionString = ....
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT TOP 10 FROM drug WHERE name LIKE #name";
cmd.Parameters.AddWithValue("#name", Dname + '%');
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
...
}
}
}
According to this previous question, the proper syntax is TOP(n), so try this:
"select TOP(10) Name
from Drug
where Name
like '" + Dname + "%' "
string selectedAreas = getSelectedAreas(areaCounts);
SqlConnection cn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select top 1 [x1] " +
"from sometable " +
"where sometable.coll = #selectedAreas" +
"order by NEWID() ";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#selectedAreas", selectedAreas);
What am I doing wrong here?
I get
Must declare the scalar variable for #selectedAreas.
#selectedAreas might become something like:
" 'nyc' or sometable.coll = 'la' or sometable.coll = 'miami' "
Edit:
I added the space as the comment below pointed out. And removed the paramter, like this:
cmd.CommandText = "select top 1 [x1] " +
"from sometable " +
"where sometable.coll = " + selectedAreas
" order by NEWID() ";
Dont know how correct it is but it works for now...
It could be the way you are running the command (which you didn't include in your question), such as in this case: Must Declare Scalar Variable