sql insert method fails when using ecrypted string - winforms

I'm using md5 to ecnrypt the user password. But whenever I try to add any records my code is throwing an error "Syntax error in INSERT INTO statement."
Here's my code
public int InsertUser(string lastName, string firstName, string username, string password, bool isAdmin)
{
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
string encryptPassword = encryptMD5(username,password).ToString();
OleDbCommand dCmd = new OleDbCommand("INSERT INTO Users (LastName, FirstName, UserName, Password) " +
"VALUES ('" + lastName + "','" + firstName + "','" + username + "','" + encryptPassword + "')", conn);
dCmd.CommandType = CommandType.Text;
try
{
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
private string encryptMD5(string username, string sPassword)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(sPassword + username);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}

Try this below, it ensure that all parameters are properly enclosed and escaped.
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
string encryptPassword = encryptMD5(username, password).ToString();
using (OleDbCommand dCmd = new OleDbCommand(
"INSERT INTO Users (LastName, FirstName, UserName, Password) " +
"VALUES (?, ?, ?, ?)", conn))
{
dCmd.CommandType = CommandType.Text;
OleDbParameter p;
dCmd.Parameters.Add(p = new OleDbParameter("#lastName", OleDbType.VarChar));
p.Value = lastName;
dCmd.Parameters.Add(p = new OleDbParameter("#firstName", OleDbType.VarChar));
p.Value = firstName;
dCmd.Parameters.Add(p = new OleDbParameter("#username", OleDbType.VarChar));
p.Value = username;
dCmd.Parameters.Add(p = new OleDbParameter("#encryptPassword", OleDbType.VarChar));
p.Value = encryptMD5(username, password);
return dCmd.ExecuteNonQuery();
}
}
}
catch
{
throw; // here should be better exception handling
}

You have a problem of higher level.
You should never create a SQL statement by concatenation of statement and values. You should bind values as parameters, then underlying framework will handle parameters and even provide them separately from the SQL statement to the server. It is much more secure way (no SQL injection is possible), with better performance and you will not get into these types of error.
If you want to understand the reason for the problem, then you should look into the actual insert statement you create and the problem will become obvious
"INSERT INTO Users (LastName, FirstName, UserName, Password) " + "VALUES ('" + lastName + "','" + firstName + "','" + username + "','" + encryptPassword + "')"
It is likely that the result of your MD5 hash or other parameters somehow breaks the SQL INSERT syntax. (it should not in most of the cases, you should provide the actual values)
You should try to execute the resulting query on the actual database to see the actual error in returns (use SQL Server Management Studio for example)
To bind parameters you should use something like that:
dCmd.Parameters.Add(new OleDbParameter("#username",username));
See some MSDN reference: OleDbCommand Parameters

Related

SQL Exception in run time [duplicate]

This question already has answers here:
Why do we always prefer using parameters in SQL statements?
(7 answers)
How to give ADO.NET Parameters
(4 answers)
Closed 5 months ago.
I am trying to add values to a database using WPF form.
This is my code:
private void Insertbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-HSIK0SQ; Initial Catalog=Demo; Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
int count = cmd.ExecuteNonQuery();
MessageBox.Show(count + " record saved successfully");
conn.Close();
}
When I am hitting the insert button:
This is the exception being thrown:
I am sure that whichever the labels and text boxes I have added they have unique name in the property. It is throwing exception while executing the query command
I am not sure what I could miss here?
Make sure to surround these values with single quotes '', and if these variables are the TextBoxes, then you have to call .Text on them to get the proper values..
cmd.CommandText = "Insert into Student values ('"+ RollNumebrtxt.Text + "','" + FNametxt.Text + "','" +
Coursetxt.Text + "');";
Better to parametrised your query..
Replace
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
With
SqlCommand cmd = new SqlCommand("INSERT INTO Student VALUES(#RollNumber, #FName, #CourseName)", conn);
cmd.Parameters.Add("#RollNumber", SqlDbType.Int).Value = int.Parse(RollNumebrtxt.Text);
cmd.Parameters.Add("#FName", SqlDbType.VarChar, 100).Value = FNametxt.Text;
cmd.Parameters.Add("#CourseName", SqlDbType.VarChar, 100).Value = Coursetxt.Text;

XAMARIN - Is it possible to do a login with a SQL query verification?

I'm looking to do an easy way to do a login without using a web API.
I would like to know if it's possible to do a login with a SQL query which is doing a verification in the user table to verify if the user is existing or not.
Using SQL server and not SQLite
[HttpPost]
public IActionResult Verify(Teacher teacher)
{
// Select the user who is trying to connect
string select = "SELECT * FROM [Db2021QuizLandStudent].[TestManagement].[Teacher] WHERE Email='" + teacher.Email + "' AND Password='" + teacher.Password + "'";
// Update the date of the last connection
string update = "UPDATE [Db2021QuizLandStudent].[TestManagement].[Teacher] SET LastConnexion = CURRENT_TIMESTAMP WHERE Email='" + teacher.Email + "' AND Password='" + teacher.Password + "'";
string query = select + ";" + update;
connectionString();
con.Open();
SqlCommand com = new SqlCommand(query, con);
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
return View("Test");
}
else
{
con.Close();
return View("Error");
}
}
I did something like that in ASP.NET and i would like to do something like that in XAMARINS.
Thanks advance for the help :D

I'm getting an error "Incorrect syntax near the keyword 'where' "

I'm trying to update a SQL Server table (connected to a WPF project) and I'm getting the message
Incorrect syntax near the keyword WHERE
What is wrong in my code?
private void Save_button_Click(object sender, RoutedEventArgs e)
{
try
{
Select("INSERT INTO [dbo].[Users](sumScore, doneLevels) VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "') WHERE [userName]= '" + ClsGlobal.userName + "'");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public DataTable Select(string selectSQL)
{
DataTable dataTable = new DataTable("dataBase");
SqlConnection sqlConnection = new SqlConnection(#"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Avraham\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\New Database.mdf ");
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = selectSQL;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
I'd try to get [and] or (and) near the word username, but this still didn't work.
This query:
INSERT INTO [dbo].Users
VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "')
WHERE [userName]= '" + ClsGlobal.userName;
Does not make sense. INSERT inserts new rows, so WHERE is not appropriate.
Perhaps you want an UPDATE:
UPDATE dbo.Users
SET sumScore = ?,
DoneLevels = ?
WHERE userName = ?;
You should be passing in ClsGlobal.sumScore, ClsGlobal.DoneLevels, and ClsGlobal.userName as parameters rather than munging the query string.

missing operator using database (unity3d)

i am using database in my game the query is giving an error of missing operator my code is
public void Execute(){
jsScript = Camera.main.GetComponent(); ReadStudent(Application.dataPath+"/dictionary.accdb","dict","word","word","=",jsScript.words);
}
internal void ReadStudent(string filetoread,string tableName, string itemToSelect, string wCol, string wPar, string wValue){
string connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + filetoread;
Debug.Log(connection);
string sqlQuery ="SELECT word FROM"+ tableName +"WHERE" + wCol + wPar+"'"+wValue+"";
OdbcConnection con = new OdbcConnection(connection);
OdbcCommand cmd = new OdbcCommand(sqlQuery,con);
DataTable dt = new DataTable("dic");
try{
con.Open();
OdbcDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
con.Close();
}
catch (Exception ex){
//text = dt.Rows[3][1].ToString();
Debug.Log(ex.ToString());
}
finally{
if (con.State!=ConnectionState.Closed){
con.Close();
}
con.Dispose();
}
if (dt.Rows.Count>0){
text = dt.Rows[0]["word"].ToString();
}
}
it is giving error : System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'word FROMdictWHEREword='MX'.
As evident by the error, your SELECT statement is lacking spaces:
[SELECT] 'word FROMdictWHEREword='MX'.
This malformed SQL is created by the following line:
string sqlQuery ="SELECT word FROM"+ tableName +"WHERE" + wCol + wPar+"'"+wValue+"";
Just add the spaces to it, and you should be fine:
string sqlQuery = "SELECT word FROM "+ tableName + " WHERE " + wCol + " " + wPar + " '" + wValue + "'";
It looks as though you're missing spaces from the command:
select word FROMdictWHEREword='MX'
should read something like
select word FROM dict WHERE word = 'MX'

Syntax error in INSERT INTO statement

I have a problem when i m connection with access database then i m getting a error Syntax error in INSERT INTO statement. and my code is :
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/Database2.accdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into data (FirstName,Email,Password,Address) values ('" +
txt_fstname.Text + "','" + txt_email.Text + "', '" +
txt_pass.Text + "', '" + txt_add.Text + "')";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Default.aspx");
plz suggest me.
"Thanks"
Password is a reserved word in Jet/ACE SQL so you must enclose it in square brackets:
string query = "insert into data (FirstName,Email,[Password],Address) values ('" +

Resources