SQL query sentence - c#

I'm working on a C# project with some data bases. I'm getting an error when executing the following function:
//Returns true if the username and password are correct. Otherwise it returns false.
public bool LogInto(string name, string pass, OleDbConnection cnx)
{
DataTable res = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter("SELECT User,Password FROM UserPassword WHERE (User='"+name+"' AND Password='"+pass+"')", cnx);
adp.Fill(res);
bool found = false;
String user = Convert.ToString(res.Rows[0]["User"]);
String password = Convert.ToString(res.Rows[0]["Password"]);
if (name==user && pass==password)
found = true;
return found;
}
So this is the full function, however I'm getting an error, I just replaced && with AND. But it still doesn't work. I'm getting ("There was an error parsing the query. // Token number, token line offset, token in error.
What's wrong with it? I had the same function but instead of taking just one row from the data table, it took the whole table and with a loop it looked the row we were looking for. However, I'm trying to do this one, just taking the row we need, because it is more efficient.
Could you guys help me? I can't find my mistake.
Thank you so much

You have some issues with the query:
The and operator in SQL is and, not &&
The query is WIDE OPEN FOR SQL INJECTION ATTACKS. You have to escape the strings to be correctly interpreted as string literals.
You can do it like this:
string query =
"SELECT User, Password FROM UserPassword WHERE Username = '" +
name.Replace("\\", "\\\\").Replace("'", "\\'") +
"' and Password = '" +
pass.Replace("\\", "\\\\").Replace("'", "\\'") +
"'";
Note: This way to escape the strings is specific to MySQL. Each database have a different set of characters that needs to be escaped, and in different ways.
If possible you should use a parameterised query instead of concatenating string into the query. That makes it easier to get it correct.

First please use parameterized one like this, with IDisposable inherited
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = #""SELECT up.User, up.Password FROM dbo.UserPassword up WHERE up.Username = #Param1" AND Password = #Param2;
cmd.Parameters.Add("#Param1", SqlDbType.Varchar).Value = 'ABC';
.............
}
second try to encrypt it or hash it, there are lot of information about hashing and encrytion on web

Related

Syntax error in UPDATE for C# using Oledb

I am creating a simple app where users create accounts. I want for the user to be able to change their password after making the account.
I am making this in C# using Oledb.
string test = "testing";
con.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = con;
string query = "UPDATE tbl_users SET password = '" + test + "' WHERE username = '" + txtLoginUsername.Text + "'";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
con.Close();
I keep getting the error:
" System.Data.OleDbException: 'Syntax error in UPDATE'"
This error is occuring in the line:
command.ExecuteNonQuery();
To clarify what Hossein has answered, when you are building your query command by adding strings together, you are wide-open to SQL-injection. Please read up on it some to protect your future development.
With reference to using "parameters". This is basically referring to a place-holder value for the query, like an "insert here" instead of you hard adding parts to the query like you were wrapping single quotes before and after the values for the password and user name.
Looking at your original query
"UPDATE tbl_users SET password = '" + test + "' WHERE username = '" + txtLoginUsername.Text + "'";
What if someone put in values of
Password: What's Up
Username: O'Conner
Your final query command when concatenated with your approach would create a value
UPDATE tbl_users SET password = 'What's Up' WHERE username = 'O'Conner'
See how the literal values have now screwed-up the string from its intent.
By using the "#" values, this is telling the SQL that hey... there will be another value coming along by the name provided, please use THAT value here. In some databases, they dont use named parameters, but "?" single character instead as a place-holder and you have to add the parameters in the exact order as they appear in the statement you are trying to prepare.
One other thing of personal preference. If your column name is UserName in I would use a parameter name like "#parmUserName" so you know it is EXPLICITLY the parameter and not accidentally just doing UserName = UserName and not get the results. A few more characters, but obvious what its purpose and where coming from works.
Now, how is that applied? Take a look again at Hossein's answer. Notice the two
command.Parameters.AddWithValue("#password", "test");
command.Parameters.AddWithValue("#username", txtLoginUsername.Text);
This is where the parameters are added to the command object. Stating, where you see the #password, use the following value I am putting here, same with #username.
Good luck going forward.
Use this syntax
Use bracket for password in query
because password is reserved word
link List of reserved world
using (var connection = new OleDbConnection("Your Connection String"))
{
var query = "UPDATE tbl_users SET [password] = #password WHERE username = #username";
using (var command = new OleDbCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#password", "test");
command.Parameters.AddWithValue("#username", txtLoginUsername.Text);
command.ExecuteNonQuery();
}
}

corresponds to your mariadb server version for the right syntax to use near '#gmail.com'

ok i have searched everywhere and all the things i find are not exactly what i'm looking for or i'm to DANG tired to see it.
I'm trying to do a search on EMAIL to see if a customer is in my database or not. IF the customer is in my database i want to fill all the textboxs so they don't have to reenter the information.
MySQL, C#, Visual Studio 2017 Community, Windows FORM Program.
here is my code that keeps giving me this error:
corresponds to your mariadb server version for the right syntax to use near '#gmail.com'
THANK YOU for any input from advanced users.
if (r)
{
dbconn();
string SelectQuery = "SELECT * FROM integercorp_TechIT.users WHERE Email="+ tb_Email.Text;
Command = new MySqlCommand(SelectQuery, connect);
MDR = Command.ExecuteReader();
if (MDR.Read())
{
tb_LastName.Text = MDR.GetString("Last");
tb_FirstName.Text = MDR.GetString("First");
tb_Address1.Text = MDR.GetString("Address1");
tb_Address2.Text = MDR.GetString("Address2");
tb_PhoneNo.Text = MDR.GetString("Phone");
tb_CellNo.Text = MDR.GetString("Cell");
tb_City.Text = MDR.GetString("City");
tb_County.Text = MDR.GetString("County");
tb_Email2.Text = MDR.GetString("Email");
tb_State.Text = MDR.GetString("State");
tb_ZipCode.Text = MDR.GetString("ZipCode");
btn_NextCustInfo.Focus();
}
}
else
{
MessageBox.Show("Welcome new Customer!!!!");
}
Try this:
"SELECT * FROM integercorp_TechIT.users WHERE Email='"+ tb_Email.Text+"'";
For email value of textbox to be recognized as string put it in single quote.
Issue is with your concatenated query, The column Email will accept a string value. which means the value should be within pair od single quotes in case of concatenated query. But that would not be a better solution here you have to go for parameterization. in that case you can form the query like the following:
string SelectQuery = "SELECT * FROM integercorp_TechIT.users WHERE Email=#mail";
Command = new MySqlCommand(SelectQuery, connect);
Command.Parameters.Add("#mail", SqlDbType.Varchar).Value = tb_Email.Text;
// Proceed with your codes
string SelectQuery = "SELECT * FROM integercorp_TechIT.users WHERE Email='"+ tb_Email.Text+"'";
just put single quote before and after Email id. Because Email accept string value

error in query in asp.net [duplicate]

This question already has answers here:
SQL Server Invalid column name when adding string value
(5 answers)
Closed 6 years ago.
Error is showing that invalid column name mustufain.
mustufain is the value of UserName.Text.toString()
string query = "select userid from register where username = " + UserName.Text.ToString() + " and " + "password = " + Password.Text.ToString();
SqlCommand cmd1 = new SqlCommand(query,connection);
connection.Open();
SqlDataReader rd1 = cmd1.ExecuteReader();
while(rd1.Read())
{
Session["checkuserid"] = rd1["userid"];
}
connection.Close();
Firstly, you should not be using string concatenation to build your queries as it can leave you vulnerable to things like SQL Injection attacks and it can cause issues with your queries being incorrect (as you are missing tick marks around your parameters) :
// This would attempt to state username = mustufain instead of
// username = 'mustufain' (and SQL doesn't know what mustufain is)
var query = "select userid from register where username = '" + UserName.Text + "' and " + "password = '" + Password.Text + "'";
A better approach using parameterization would look like the following, which avoids the incorrect syntax and offers you protection against any nasty injections :
// Open your connection
using(var connection = new SqlConnection("{your connection string}"))
{
// Build your query
var query = "SELECT TOP 1 userid FROM register WHERE username = #username AND password = #password";
// Build a command (to execute your query)
using(var command = new SqlCommand(query, connection))
{
// Open your connection
connection.Open();
// Add your parameters
command.Parameters.AddWithValue("#username",UserName.Text);
command.Parameters.AddWithValue("#password",Password.Text);
// Execute your query
var user = Convert.ToString(command.ExecuteScalar());
// If a user was found, then set it
if(!String.IsNullOrEmpty(user))
{
Session["checkuserid"] = user;
}
else
{
// No user was found, consider alerting the user
}
}
}
Finally, you may want to reconsider how you are storing your credentials (in clear text). ASP.NET offers a wide variety of providers that can help handle this process for you so that you don't have to do it yourself.
You are trying to concatenate strings to build an sql query and, as usual, you get errors. In your specific case you forget to enclose your string values between single quotes. But the only correct way to do this query is by the way of a parameterized query
string query = #"select userid from register
where username = #name and password = #pwd";
using(SqlCommand cmd1 = new SqlCommand(query,connection))
{
connection.Open();
cmd1.Parameters.Add("#name", SqlDbType.NVarChar).Value = UserName.Text;
cmd1.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = Password.Text;
using(SqlDataReader rd1 = cmd1.ExecuteReader())
{
....
}
}
Notice also that storing passwords in clear text in your database is a very bad practice and a strong security risk. On this site there are numerous questions and answers that explain how to create an hash of your password and store that hash instead of the clear text
For example: Best way to store passwords in a database

How to Update paragraph from mysql table using c#

I tried to update a paragraph from mysql table,but i got error like this
"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's first-ever super-villainess."
My mysql Query
cmd.CommandText = "UPDATE `moviemaster` SET `Runtime`='" + runtime + "',`DateMasterId`='" + dateid + "',`Trailer`='" + trailer + "',`Synopsis`='" + synopsis + "' WHERE `MovieMasterId`='" + movieid + "'";
I got error in 'synopsis',it's a big data containing a large paragraph.If i romove 'Synopsis' section from the query,everything working fine.What exactly the problem.How can i resolve this?
#SonerGönül:Ok,fine.. then please show me an example of parameterised
query
Sure. I also wanna add a few best practice as well.
Use using statement to dispose your connection and command automatically.
You don't need to escape every column with `` characters. You should only escape if they are reserved keywords for your db provider. Of course, at the end, changing them to non-reserved words is better.
Do not use AddWithValue method. It may generate upexpected and surprising result sometimes. Use Add method overload to specify your parameter type and it's size.
using (var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"UPDATE moviemaster
SET Runtime = #runtime, DateMasterId = #dateid, Trailer = #trailer, Synopsis = #synopsis
WHERE MovieMasterId = #movieid";
cmd.Parameters.Add("#runtime", MySqlDbType.VarChar).Value = runtime; ;
cmd.Parameters.Add("#dateid", MySqlDbType.VarChar).Value = dateid;
cmd.Parameters.Add("#trailer", MySqlDbType.VarChar).Value = trailer;
cmd.Parameters.Add("#synopsis", MySqlDbType.VarChar).Value = synopsis;
cmd.Parameters.Add("#movieid", MySqlDbType.VarChar).Value = movieid;
// I assumed your column types are VarChar.
con.Open();
cmd.ExecuteNonQuery();
}
Please avoid using inline query. Your database can be subjected to SQL Injection. See this example, on what can be done using SQL Injection.
And use paramterized query instead. Here is the example taken from here. This way, even if your string has special characters, it will not break and let you insert/update/select based on parameters.
private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = #param_val_1 AND VAL_2 = #param_val_2;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.AddWithValue("#param_val_1", val1);
m.Parameters.AddWithValue("#param_val_2", val2);
level = Convert.ToInt32(m.ExecuteScalar());
return true;
}
and finally, your query will become
cmd.CommandText = "UPDATE `moviemaster` SET `Runtime`= #param1,`DateMasterId`= #dateid, `Trailer`= #trailer,`Synopsis`= #synopsis WHERE `MovieMasterId`= #movieid";
cmd.Parameters.AddWithValue("#param1", runtime);
cmd.Parameters.AddWithValue("#dateid", dateid);
cmd.Parameters.AddWithValue("#trailer", trailer);
cmd.Parameters.AddWithValue("#synopsis", synopsis);
cmd.Parameters.AddWithValue("#movieid", movieid);

Comparing against database value

What I am trying to do is grab the current logged in users username and compare that against a database which contains users, and also includes an Active flag and an Admin flag. I want to compare the current logged in user in the tbl_Person table and their respective user in the table to see if they are marked as Active and Admin. If both are true, they get access to an Admin page. I have the below so far which isn't working. Some of which I know why, some I don't. I think I am on the right track, that being said I am sure I am not doing it correctly. I know you use ExecuteScalar() to return something along with OUTPUT in the query string but couldn't get that to work. The other glaring issue is that I am trying to return integers when the username is a string and the active and admin flags are Bools. I know that I only have Active in there are the moment. I was trying to get that to work before adding in something else.
I read that with the ExecuteScalar, you could Parse and convert ToString, but that didn't work and I found evidence that this might not be the correct thing to do, but I'm really not sure.
I have got a few different errors. Type errors, invalid column when I've tried to do the OUTPUT. With OUTPUT I tried as just OUTPUT and because I know when returning after inserting, you do inserted.name. I tried selected.name as a hunch, but that didn't work.
I was thinking that if I pulled the info, concatenated them and then did a comparison, that this would do what I want, but I am open to other suggestions. Thanks.
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HSEProjRegConnectionString1"].ConnectionString);
conn.Open();
SqlCommand sqlUserName = new SqlCommand("SELECT [username] FROM [tbl_Person]", conn);
SqlCommand sqlActive = new SqlCommand("SELECT [active] FROM [tbl_Person]", conn);
int result1 = ((int)sqlUserName.ExecuteScalar());
int result2 = ((int)sqlActive.ExecuteScalar());
string userInfo = result1 + "." +result2;
string userName = userName + "." +result2;
if (userInfo == userName)
{
Woo, you have access.
}
else
{
Sorry, but no.
}
The Query isn't final either. Once it is working, I'll change it to a parameterised query.
Okay, consider the following code:
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HSEProjRegConnectionString1"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT [active] FROM [tbl_Person] WHERE username = #username", conn))
{
// since we can literally filter the results, if something comes back
// we know they are registered
cmd.Parameters.AddWithValue("#username", userName);
var res = cmd.ExecuteScalar();
bool registeredAndActive = (bool)res;
// unless of course `[active]` is an INT -then do this
bool registeredAndActive = (int)res == 1 ? true : false;
// but really -set [active] up as a BIT if it's not **and**
// please make it non-nullable :D
}
}
I'm pretty sure it does what you want. But it also shows you some best practices like:
Leverage the using statement for all IDisposable objects.
Filter the query as much as you can and make only one round trip.

Categories