Database query in SQL Server side.
declare #password varchar(100) = '12345aA!'
select user_id, username from tblusers
where password=CONVERT(NVARCHAR(32),HashBytes('MD5', #password), 2);
This query works fine and below is the output. It gives one record, ok?
Below is C# code to validate password
var query = "select user_id from tblusers";
query += " where password=CONVERT(NVARCHAR(32), HashBytes('MD5', #password), 2);";
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = _config.GetConnectionString("backend");
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#password", form.password);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
//not entering in this scope
}
}
}
}
Due to some reasons c# code is unable to validate password through sql query. Am I missing anything?
Related
I am trying to update username from MVC .Net C# after connecting Postgres SQL.
I am able to establish the connection and if I run select command I am able to get the result.
But when I am trying to update record no error comes but updated count comes 0. Record available in database.
Can you please suggest what could be the reason.
using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
{
string query = string.Format("UPDATE um_user SET um_user_name='{0}' WHERE um_user_name='{1}'", updatedUser, userNameToBeUpdated);
con.Open();
NpgsqlCommand comn = new NpgsqlCommand(query, con);
comn.Connection = con;
updatedRows = comn.ExecuteNonQuery();
comn.Dispose();
con.Close();
}
I have added using parameter as well with the following code but still getting 0 updtaed rows.
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "update um_user set um_user_name=#newName where um_user_name=#oldName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter("#newName", updatedUser));
cmd.Parameters.Add(new NpgsqlParameter("#oldName", userNameToBeUpdated));
updatedRows = cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
}
I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID, #IngredientNaam";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
I want to insert data to the tables Voorraad and Ingredient. In the tables Voorraad there must IngredientID, AantalInVoorraad, MinimumVoorraad and Categorie be in the table after instert.
In the table Ingredient there must be an new Ingredientnaam be made. When i filling in the text boxes and after hitting the button insert i get the error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#MinimumVoorraad'.'
Please help me!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID,
#IngredientNaam)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
Does anybody know maybe another way to insert data to multiple tables in the datbase?? I've searched the whole internet for an answer but i can't find the right solution.
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)";
and
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(#IngredientID, #IngredientNaam)";
Your insert statements are missing the closing bracket for the values.
Add a using Statement for the SQlConnection and SQLCommand, will make it easier to read and debug.
using (SqlConnection con = new SqlConnection(#"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(#IngredientID, #IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
I am trying to call an external stored procedure (calls an RPG program). I keep getting the following error:
"Exception Details: IBM.Data.DB2.iSeries.iDB2SQLErrorException: SQL0104 Token #SSN was not valid. Valid tokens: :."
Here is my code:
using (iDB2Connection conn = new iDB2Connection(_CONNSTRING))
{
conn.Open();
string sqlStatement = "MPRLIB.SIGNTIMESHEET (#SSN, #SIGNATURE, #WORKSTATION, #TOTALHOURS, #COMMENT)";
//string sqlStatement = "MPRLIB.SIGNTIMESHEET (?, ?, ?, ?, ?)";
iDB2Command cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStatement;
cmd.Parameters.Add("#SSN", timesheet.EmployeeUniqueKey.ToString("0000000000"));
cmd.Parameters.Add("#SIGNATURE", timesheet.EmployeeTypedName);
cmd.Parameters.Add("#WORKSTATION", timesheet.EmployeeSignedComputer);
cmd.Parameters.Add("#TOTALHOURS", GetJobHoursTotal(timesheet.Id).ToString("00000.000").Replace(".", ""));
cmd.Parameters.Add("#COMMENT", timesheet.EmployeeComments);
cmd.ExecuteNonQuery();
conn.Close();
}
I can't seem to figure out what is happening or why I am getting the above error. My connection string looks like:
private const string _CONNSTRING = "DataSource=192.168.50.200;DefaultCollection=QMFILES;Naming=sql;UserID=XXX;Password=XXX;";
Could it be a library list issue? The program just references one file that is in the library list. Any suggestions?
Try like this:
using (var conn = new iDB2Connection(_CONNSTRING))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "MPRLIB.SIGNTIMESHEET";
cmd.Parameters.Add("#SSN", timesheet.EmployeeUniqueKey.ToString("0000000000"));
cmd.Parameters.Add("#SIGNATURE", timesheet.EmployeeTypedName);
cmd.Parameters.Add("#WORKSTATION", timesheet.EmployeeSignedComputer);
cmd.Parameters.Add("#TOTALHOURS", GetJobHoursTotal(timesheet.Id).ToString("00000.000").Replace(".", ""));
cmd.Parameters.Add("#COMMENT", timesheet.EmployeeComments);
cmd.ExecuteNonQuery();
}