Prepare statement like clause with chinese character - c#

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+"%");

Related

Repeater Search Query String

How can I make my select line in C# check if news_title is like my query string named Search?
This is what I have tried without success. It's supposed to then fill a Repeater with results that are like the query string.
// Get data from database/repository
static DataTable GetDataFromDb()
{
string searchquery = HttpContext.Current.Request.QueryString["Search"].ToString();
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
con.Open();
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE ([news_title] " +
"LIKE '%' + " + searchquery + " + '%') Order By news_postdate", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
It should be '%" + searchquery + "%'. However this kind of string concatenation is open for SQL injection. Try parameterized queries instead, something like this :
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title] " +
"LIKE #Search Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search","%" + searchquery + "%");
Or:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title]" +
" like '%' + #Search+ '%' Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search",searchquery);
Although specify the type directly and use the Value property is more better than AddWithValue. Have a look at this Can we stop using AddWithValue() already?

Why Am I getting this error in my SELECT statement in C# WinForms to MySQL Database?

I am getting this error:
Unknown column 'admin' in 'where clause'
This is my code for the Log-In button:
mycon.Open();
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = " + textBox1.Text + "";
cmd = new MySqlCommand(cmdstr, mycon);
dr = cmd.ExecuteReader();
string inputpw = "";
string dbpw = "";
while (dr.Read())
{
inputpw = maskedTextBox1.Text;
dbpw = (dr["user_pw"].ToString());
}
dr.Close();
mycon.Close();
I can't quite get why I get that error since my Select statement is the same with all the other select statements I see online
enclose the textbox value in single quotes
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = '" + textBox1.Text + "'";
Edit:
As commented by Tigran. Use Parametarized queries instead just concatenating values from the controls
I can't quite get why I get that error
Then start debugging. Put a breakpoint on the cmd = line and inspect cmdstr's contents. You'll see the query is:
SELECT * FROM usersettingsdb WHERE user_ID = admin
Then you'll see you need to put quotes around the username. Now go read about SQL injection, parametrized queries and DAL's.
You need an extra set of " " in your where clause surrounding the textbox1.Text otherwise you are not passing it a string.
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = \"" + textBox1.Text + "\"";
Do something like this..
string cmdstr = string.Format("SELECT * FROM usersettingsdb " +
"WHERE user_ID = '{0}'", textBox1.Text.Replace("'","''"));
Replacing ' with '' because sql think ' as escape character.
But going with Parameterized queries is rocommended.

Odac ORA-00911: invalid character

I am writing a C# code that connects to ODAC. I think my query got no errors, but I get this error, I don't know how to solve.
This is my query
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id +
"' AND APPID = '" + app_id + "' ;";
Can any one figure out what is wrong in here?
Your query is vulnerable for a security issue called SQL injection!
You should NEVER use string concatenation for building a query from strings (some SQL, some parameters)... Use always parameterized queries...
Sample code:
comm.BindByName = true;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = :login_id AND APPID = :app_id";
comm.Parameters.AddWithValue ("login_id", login_id);
comm.Parameters.AddWithValue ("app_id", app_id);
Why there is a ; in your sql command? Try this;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id + "' AND APPID = '" + app_id "';
By the way, you should always use parameterized queries. This clearly open for an sql injection. For your query, use like this;
string commandText = "SELECT * FROM ZAEDBA WHERE USER_ID = #login_id " + AND
+ "WHERE APPID = #app_id;";
command.Parameters.Add("#login_id", SqlDbType.Int);
command.Parameters["#login_id"].Value = login_id;
command.Parameters.Add("#app_id", SqlDbType.Int);
command.Parameters["#app_id"].Value = app_id;

"Must declare the scalar variable" for parameter (C# SqlCommand)

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

Parameterize a SELECT ROWCOUNT sql statement

I am using VS2005 C# and SQL Server 2005.
I have a a few SQL queries which I am converting them from using parameters instead concatenations for SQL injection prevention.
Below is a SELECT query which is parameter-ed:
string loggedinuser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [UserTable] where [" + DropDownList1.Text + "] like #searchtb AND [LoggedInUser] LIKE #userlog";
SqlDataSource1.SelectParameters.Add("searchtb", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("userlog", "%" + loggedinuser+ "%");
The above sql query searches for records base on the user's input in a search textbox and return results which matches the search input and username in the database.
I have another SQL query which is also a SELECT statement. However, this time it does not use SqlDataSource, but using cmd instead. Thus I need some help in converting the SQL statement below to parameter form:
string loggedinuser = (User.Identity.Name);
string stmt = "SET ROWCOUNT 1 SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [LoggedInUser] LIKE '%"+loggedinuser +"%'";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
This SQL query searches for number of records that the user is trying to search base on his search input and username. And if countuser returns a 0 value, I will prompt the user after that.
I need help in converting the 2nd SQL statement into parameter form.
Thank you.
Try,
string stmt = "SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "]
like #searchTb AND [LoggedInUser] LIKE #loggedinuser";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
cmdCount.Parameters.Add("#searchTb",SqlDbType.VarChar,40).Value="%" + searchTB.Text + "%";
cmdCount.Parameters.Add("#loggedinuser",SqlDbType.VarChar,40).Value="%" + loggedinuser + "%";
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
Using stored procedures is your best bet, but if you cannot use them, this code should work:
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id", conn);
SQLParameter parm = myCommand.SelectCommand.Parameters.Add("#au_id",
SqlDbType.VarChar, 11);
Parm.Value = Login.Text;
This is from the MSDN article on SQL injection.
http://msdn.microsoft.com/en-us/library/ms161953.aspx

Categories

Resources