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
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 need to insert 388 datas per minute to local Database.
At first when the table is Empty, I only need 5 second to Insert to database.
But when the table gets larger, the program efficacy slow down to more than one minute when the amount of rows comes to 1,026,558.
And the useage of CPU is 100%. It's unusual.
here is my code:
public static void dataToDB(String[] routeIDArray,String[] levelArray,String[] valueArray,String[] travelTimeArray, int amountOfData)
{
MySqlConnection con = new MySqlConnection(connStr);
MySqlCommand cmd = null;
MySqlDataReader rdr = null;
String sqlCmd, updateSqlCmd = "UPDATE `datetimetable` SET ";
for(int counter = 0; counter < amountOfData; counter++)
{
sqlCmd = "ALTER TABLE `datetimetable` ADD COLUMN IF NOT EXISTS `" + routeIDArray[counter] + "` INT NULL;"
+ "INSERT INTO `roadvalue`.`data` (`level`,`value`,`traveltime`) VALUES ("
+ levelArray[counter] + ","
+ valueArray[counter] + ","
+ travelTimeArray[counter] + ");"
+ "SELECT LAST_INSERT_ID() FROM `data`;";
cmd = new MySqlCommand(sqlCmd, con);
con.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
updateSqlCmd += "`" + routeIDArray[counter] + "` = " + rdr[0] + ",";
rdr.Close();
}
updateSqlCmd = updateSqlCmd.TrimEnd(',');
updateSqlCmd += " WHERE EXISTS (SELECT * WHERE dateTime = '" + dateTime.ToString("yyyy-MM-dd HH:mm:00") + "');";
cmd = new MySqlCommand(updateSqlCmd, con);//update data key to datetimetable
cmd.ExecuteNonQuery();
Console.WriteLine("Done.");
con.Close();
}
public static void checkDateTimeExisted()
{
MySqlConnection con = new MySqlConnection(connStr);
MySqlCommand cmd;
String sqlCmd;
sqlCmd = "INSERT INTO `datetimetable` (`dateTime`) SELECT * FROM (SELECT '" + dateTime.ToString("yyyy-MM-dd HH:mm:00")
+ "') AS tmp WHERE NOT EXISTS(SELECT `dateTime` FROM `datetimetable` WHERE `dateTime` = '" + dateTime.ToString("yyyy-MM-dd HH:mm:00") + "') LIMIT 1; ";
con.Open();
cmd = new MySqlCommand(sqlCmd, con);
cmd.ExecuteNonQuery();
con.Close();
}
And Mysql Engine is InooDB, table "data" has one Auto_Increment Primary key, table "datetimetable" has an Auto_Increment Primary key and a not duplicate datetime as index.
What have I done wrong?
I find the answer, the command "SELECT LAST_INSERT_ID() FROM data;" should add LIMIT 1 or it will get all the ID kill the performance.
Do not use ALTER TABLE in a loop -- Plan ahead and provide all the columns before starting.
Do not use multiple statements in a single string. This has security implications, etc.
Do not use WHERE EXISTS... when (I think) a simple WHERE would work.
If there is UNIQUE(datetime), then the final INSERT can be simply
INSERT IGNORE INTO datetimetable
(datetime)
VALUE
('...');
Do batch inserts unless you need the LAST_INSERT_ID(). LIMIT 1 should not be necessary.
Do not 'Normalize' datetime values; it only slows things down. Just put the datetime as is in the main table.
I'm having trouble deleting(DELETE) rows. Everytime I add column names in my string sql it shows the error "Syntax error (missing operator) in query expression ". This is my code:
OleDbConnection myCon = new OleDbConnection("provider = Microsoft.Jet.OLEDB.4.0;DataSource = '" + fileLocation + "'; Extended Properties=Excel 8.0;");
OleDbCommand myCmd = new OleDbCommand();
myCmd.Connection = myCon;
string sql = "DELETE * FROM [" + tablename + "$] where _date = '" + full_date + "'";
myCmd.CommandText = sql;
myCon.Open();
myCmd.ExecuteNonQuery();
myCon.Close();
For Example my string sql value is
"DELETE * FROM [Sheet1$] where _date = '03 09 2015'"
It would produce this error:
Syntax Error (missing operator) in query expression "_date = '03 09
2015'"
I have no problems when inserting data in my excel file but when it comes to delete it says this error.
Try to use this i.e., remove the *, it is not required with DELETE statement:
string sql = "DELETE FROM [" + tablename + "$] where _date = '" + full_date + "'";
Also the value which you are getting in full_date doesnt seem to be in correct format. Do check the value which you are getting in full_date with the format in which you are having in your table.
On a side note:
You code is prone to SQL Injection. You need to use prepared statement to avoid that.
You have syntax error in your query, please remove * from your query, hence your query may look like the following: you can check the syntax here:
string sql = "DELETE FROM [" + tablename + "$] where _date = '" + full_date + "'";
And the query you are using will opens a wide way for sql injection, so better approach is to use parameterized queries instead.
you should try
string strQuery= "DELETE FROM #TableName where _date = '#date'";
usin (SqlCommand cmd = new SqlCommand(strQuery)){
cmd.Parameters.AddWithValue("#TableName", tablename+"$" );
cmd.Parameters.AddWithValue("#date", full_date );
myCon.Open();
cmd.ExecuteNonQuery();
}
I've built an app in vs 2012 that is supposed to be able to select, insert, update, delete info from a sql server 2012 database. At first I put some data into the db using sql server. I built my select queries to test them out and they worked. After this I built my insert query and tested it out. It also works. But if I try to retrieve data that I have inserted, it doesn't retrieve anything.
Here's an example of one of my select queries:
query = "SELECT P.Denumire, P.Pret, P.Cantitate, P.Reducere, P.Pret_redus, " +
"S.Stoc_magazin, S.Stoc_depozit " +
"FROM Produse P, Stoc_intern S " +
"WHERE S.ID_produs IN " +
"(SELECT P.ID_produs " +
"FROM Produse " +
"WHERE P.Denumire LIKE '%" + tb_s_name.Text + "%')";
SqlDataAdapter da = new SqlDataAdapter(query, c);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
q_res.DataSource = dt;
And here's and example of one of my insert queries:
query = "Insert INTO Produse " +
"(Denumire, Pret, Cantitate, Reducere) " +
"Values(#Denumire, #Pret, #Cantitate, #Reducere)";
SqlCommand cmd = c.CreateCommand();
cmd.Connection = c;
cmd.CommandText = query;
cmd.Parameters.Add("#Denumire", SqlDbType.NVarChar, 50).Value = tb_op_name.Text;
cmd.Parameters.Add("#Pret", SqlDbType.Float).Value = tb_op_pv.Text;
cmd.Parameters.Add("#Cantitate", SqlDbType.NVarChar, 50).Value = tb_op_cantitate.Text;
cmd.Parameters.Add("#Reducere", SqlDbType.Float).Value = tb_op_red.Text;
cmd.ExecuteNonQuery();
Both queries work, it's just that if I submit the insert query and after try to select something with the select query, it does not retrieve anything although the information exists in the database. I checked by opening the db in sql server after executing the insert query from my vs built app.
Here's the connection string also:
SqlConnection c = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Application.StartupPath + #"\DB\Supermarket.mdf;Integrated Security=True;MultipleActiveResultSets=true;Connect Timeout=30");
Please use different SqlConnections for each procedure.
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.