Unable to do a query using a textbox input - c#

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)

Related

SQLite searching for user in table

// This returns a count of 1, so the table does exist, and I know the user exists becaue I have just added him in...
Int32 tableCount = database.Query(map, "SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'UserTable'", ps).Count;
//but when I try this the count is 0....what am I doing wrong?
Int32 tableCount2 = database.Query(map, "SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'UserTable' AND NameOfUser = '" + personsName + "'", ps).Count;
t
rying to see if the user exists...what am I doing wrong?
SQL Injections
First, I want to say that this code is vulnerable to SQL Injections, .
Why does the query not work?
Because 'NameOfUser' is not a column of sqlite_master, but it is a column of UserTable, I suppose.
sqlite_master consists of the following columns:
type
name
tbl_name
rootpage
sql
How can I make it work?
Int32 tableCount2 = database.Query(map, "SELECT * FROM UserTable WHERE NameOfUser = '" + personsName + "'", ps).Count;
But, as said before, you better use C# SQLite prepared statements to prevent SQL injection, check this: C# SQLite tutorial and search for 'prepared'
Please mark as answer when it worked.
CU

C# - ODBC Parameters acting up

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);

How to return MySQL table entries by specified value ASP.net/C#

I know its probably something simple but its been driving me nuts for 2 days now
In short, what I want to do is return all of the entries from a specific table based on a value fed into the sql string from a label that holds the appropriate value
This is what I have currently, and it works, but I don't want it to be hardcoded to 'admin':
sqlString = "SELECT * FROM mail WHERE fromuser = 'admin'";
The above returns the entries in the table where the fromuser value is 'admin'
Like I said it works fine. What I want to do is something more like this:
sqlString = "SELECT * FROM mail WHERE fromuser = " + lblUsername.Text;
Where the lblUsername.Text is the value of the currently logged in user (in this case its admin just like before)
So my question is how to I feed the label value into the sql string so that I don't need to hardcode it as 'admin' so that what is returned changes with the value of lblUsername.Text?
I think your first issue is you are missing the quotes when you are building the sql. So your query should look like
sqlString = "SELECT * FROM mail WHERE fromuser = '" + lblUsername.Text + "'";
But the that would be a horrible query to run against your database, because you would be very vulnerable for sql injection. Try parameterized query instead.
I'm assuming your connection string is set in connectionString variable
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM mail WHERE fromuser = #fromUser", connection);
cmd.Parameters.Add(new MySqlParameter("fromUser", lblUsername.Text));
MySqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows){
//do all your reading.
}
connection.Close();
Also, I would suggest you to look into Dapper dot net, which is an excellent ORM to use rather than this naive ADO.NET code
try
var textInLabel = lblUsername.Text;
sqlString = "SELECT * FROM mail WHERE fromuser ='" + textInLabel + " '";
TRY THIS
sqlString = "SELECT * FROM mail WHERE fromuser = '"+ lblUsername.Text+"'";

How to use MySql select with c#

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 + "'";
^

Escape Character for SQL in C#

I want to add a simple select statement in my C# code. Sample looks like below. The value like y in fname comes from a parameter.
//select lname from myTable where fname = 'y'
Here's what I m doing. I m obviously getting Sql Exception. How do I correct it? Thanks.
string strOrdersOrigSQL = "SELECT LastName FROM Employees";
// Concatenate the default SQL statement with the "Where" clause and add an OrderBy clause
strOrdersSQL = strOrdersOrigSQL + "where FirstName ="+ 'strFname';
You should never concat sql commands by hand. Use the class SqlCommand and add parameters
using (var cmd = new SqlCommand("SELECT LastName FROM Employees where FirstName = #firstName", conn))
{
cmd.Parameters.AddWithValue("#firstName", strFname);
var reader = cmd.ExecuteReader();
}
You dont need to worry about escaping charaters in Sql when passing from C#
Sql does it for you
all you need to do si:
string strOrdersOrigSQL = "SELECT LastName FROM Employees Where FirstName = #FirstName"
Nwo you can pass the value for #FirstName via SqlParameter this will protect you query from Sql injection
Some other problems with your query are that you are missing a space and the quotes go inside the string literal:
strOrdersSQL = strOrdersOrigSQL + " where FirstName = '"+ strFname + "'";
// ^ ^ ^
But this still won't work if the variable contains a quote character or backslash.
Instead of trying to escape the string you should use parameterized queries.
But it can be done as
string strOrdersOrigSQL = "SELECT LastName FROM Employees";
// Concatenate the default SQL statement with the "Where" clause and add an OrderBy clause
strOrdersSQL = strOrdersOrigSQL + " where FirstName ='"+ strFname + "'";
This is not proper way of doing it since it can be affected by SQL Injection. Use parameterised queries instead.
First of all, use SqlCommand. But if you choose to write direct SQL, it is OK as long as you escape your input. You should be very careful with this and know what you are doing. Else, your code presents an SQL Injection. Here is the correct code:
string strOrdersOrigSQL = "SELECT LastName FROM Employees ";
// Concatenate the default SQL statement with the "Where" clause and add an OrderBy clause
strOrdersSQL = strOrdersOrigSQL + "where FirstName = '" + strFname.Replace("'", "''") + "'";
Assuming that strFname is a variable.

Categories

Resources