So, I am trying to change the design of my program in order to prevent SQL injection, seeing how old SQL strings were made by concatenating TextBoxes with a preset string.
I am using the ODBC driver over a DB2 database.
Thing is, it works in some cases, in others it just doesn't.
Let me give you an example:
Old code:
App.Comando.CommandText = "SELECT NOMUSU, CodEmp FROM DB.Users WHERE CODUSU = '" + txt_usuario.Text + "' AND PASUSU = '" + txt_password.Password + "'";
New code:
App.Comando.CommandText =
"SELECT NOMUSU, CodEmp FROM DB.Users WHERE CODUSU = ? AND PASUSU = ?";
App.Comando.Parameters.AddWithValue("#codusu", txt_usuario.Text);
App.Comando.Parameters.AddWithValue("#pass", txt_password.Password);
This one works perfectly.
However, this one, doesn't. Doesn't throw any error, just comes back seemingly empty.
Old code:
App.Comando.CommandText = "SELECT CODMAR FROM DB.Marcas AS MARCAS WHERE DESMAR = '" + marca + "'";
New code:
App.Comando.CommandText = "SELECT CODMAR FROM DB.Marcas AS MARCAS WHERE DESMAR = ?";
App.Comando.Parameters.AddWithValue("#marca", marca);
Just in case you need it,
string marca = txt_marca.Text.Trim().ToUpper();
In this case, the new code doesn't work, the old one did. I've been pulling my hair out, it just makes no sense.
Thanks for your time!
have your set the type of command?
App.Comando.CommandText = "SELECT CODMAR FROM DB.Marcas AS MARCAS WHERE DESMAR = ?";
App.Comando.Parameters.AddWithValue("?marca", marca);
Related
This is my code:
string query = "SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = " + jobId + ".00";
SqlDataReader reader = new SqlCommand(query, sqlConn).ExecuteReader();
This is my data:
I want to fetch multiple rows with the exact JOBBNR, but this returns nothing.
EDIT:
The query was working, it was just me being stupid and not searching in the right table. Sorry for wasting anyones time trying to help.
Include the jobId in single quotes. Modify your query to following:
"SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = '" + jobId + ".00'"
Observe the single quote around jobId.
Looking at the comments, I suspect the datatype of JOBBNR is float; NOT decimel. float datatype internally contains multiple precision, so when you try to match them in WHERE = clause, you may not get result due to mismatched precision.
There are multiple ways to handle this problem. Try something like following:
WHERE JOBBNR BETWEEN 1200.00 AND 1200.01
OR
"WHERE JOBBNR BETWEEN '" + jobId + ".00' AND '" + jobId + ".01'"
I am trying to allow user to enter details inside a textbox and use that information to run a SQL query. It works when I hard code everything for example:
string query = "SELECT * FROM PERSONS WHERE Name='Samuel'";
When I try to use the textbox instead as follows, it returns an error. I am definitely entering the correct name Samuel in the textbox. I ran a messagebox to check if the textbox is registering the name correctly and yes, it is correct. Please advice if you see anything wrong. Thanks.
name = textbox4.Text;
MessageBox.Show(name);
string query = "SELECT * FROM PERSONS WHERE Name=" + name;
What language? C#?
string query = string.Format("SELECT * FROM PERSONS WHERE Name = '{0}'", SanitizeSql(name));
Or you could be cool and use https://github.com/markrendle/Simple.Data then it would just be
IEnumerable<Person> people = db.Persons.FindAllByName(name);
and this also takes care of SQL injection and is database independent (so you can switch from MSSQL to MySQL to MongoDB...)
You forgot quotes. Change query like below:
string query = "SELECT * FROM PERSONS WHERE Name='" + name + "'";
string query = "SELECT * FROM PERSONS WHERE Name=" + name;
Should be
string query = "Select * From PERSONS Where name = '" + name + "'" ;
Use name=txbox.Text;
dbLog.Open("SELECT * FROM Persons WHERE Name='" & name & "'", dbCon, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
Can anyone tell whats wrong with my code? I have tried a million different things and I cant seem to make it work. I need to make a select in my mysql database and use the id from the table with the specified name I take from a combobox.
I took that name from the combobox and put it into a variable named "nomeres", now I need to do a select with it and take the id from that name from the database. Everything I try to do results in a mysql syntax error in line 1, but I've tried alot of things and its always the same. The database is fine, I tried the select directly from it myself, no tables or columns names are incorrect. This is the code im using:
MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection("Persist Security Info=False;server=localhost;database=notas;uid=root;password=" + dbpwd);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres;
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Erro" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
}
as others have already pointed you towards right direction,
i would like to suggest you to use parameterised queries to avoid SQL injection attacks.
Your query is open to SQL injection attacks so please read here
Try This: using parameterised SQL queries
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValue("#nome",nomeres);
You need to terminate the string in the query:
"SELECT id from residentes WHERE nome ='" + nomeres + "'"
In general, when trying to debug this type of code, it helps to print out the query string after all substitutions have been made.
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres + "';";
actually you misses the semicolon of the query that have to enter within the quotes. and the second semicolon is for the end of statement.
But I preffer wo write commands like
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValues("#nome", variableName);
then execute the query and retrieve your results.
Missing single quote:
"SELECT id from residentes WHERE nome ='" + nomeres + "'";
^
im using access database and im getting this weird error...
missing semicolon at the end of sql statement...
p.s i try to put the semicolon but again same thing...error again...
please help.
this is the code and the error start at Insert Into Statement :
oleDbConnection1.Open();
Int32 sasia_aktuale;
Int32 sasia_e_shtuar = Convert.ToInt32(textBox1.Text.Trim());
string kerkesa = "select * from magazina where emri = '"+listBox1.SelectedItem+"'";
OleDbCommand komanda = new OleDbCommand(kerkesa, oleDbConnection1);
OleDbDataReader lexo = komanda.ExecuteReader();
lexo.Read();
sasia_aktuale = Convert.ToInt32(lexo.GetValue(2).ToString());
lexo.Close();
Int32 sasia_totale = sasia_aktuale + sasia_e_shtuar;
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "') where emri= '" + listBox1.SelectedItem + "'";
oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Sasia per produktin " + listBox1.SelectedItem + " u shtua me sukses!", "Sasia u shtua");
oleDbConnection1.Close();
You are mixing a WHERE clause with an INSERT statement, the two do not go together:
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "')";
Do you mean an UPDATE statement?
I'd also advise you to look up SQL injecton, and using SqlParameters to build your queries. Your code, currently is very insecure.
I can see you are after an UPDATE command. The INSERT SQL command is just going to insert whatever you give it. An example of an UPDATE command, using SqlParameters to help avoid SQL injection, is below, although this is untested as I obviously don't have access to your setup (nor am I doing this with an IDE):
var updateCommand = new OleDbCommand("UPDATE magazina SET sasia = #sasia_totale WHERE emri = #emri");
updateCommand.Parameters.AddWithValue("#sasia_totale", sasia_totale);
updateCommand.Parameters.AddWithValue("#emri", listBox1.SelectedItem.ToString());
oleDbDataAdapter1.UpdateCommand = updateCommand;
oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.