Why does the value not change in database after UPDATE statement? - c#

The following subroutine should update the text in the database to new user input, however, when I check the database nothing has changed?
private void UpdatePassword(string Username, string NewPassword)
{
string SQLStatement =
"UPDATE [Login Details] SET [PASSWORD] = #password WHERE [USERNAME] = #username";
OleDbConnection connString = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = TrigonometryToolDatabase.accdb");
OleDbCommand cmd = new OleDbCommand(SQLStatement, connString);
cmd.Parameters.AddWithValue("#username", Username);
cmd.Parameters.AddWithValue("#password", NewPassword);
connString.Open();
cmd.ExecuteNonQuery();
connString.Close();
}

Parameters in MS Access / OleDB is positional - they are NOT matched on name (like in ADO.NET / SQL Server) - but on their position in the query string.
You have
string SQLStatement =
"UPDATE [Login Details] SET [PASSWORD] = #password WHERE [USERNAME] = #username";
so the first parameter you pass in will need to be the password, the username comes second.
However, in your code, you're doing it just the other way around:
cmd.Parameters.AddWithValue("#username", Username);
cmd.Parameters.AddWithValue("#password", NewPassword);
So flip these two lines, and you should be good:
cmd.Parameters.AddWithValue("#password", NewPassword);
cmd.Parameters.AddWithValue("#username", Username);

Related

Insert String value into Database C#

I've got my passwords to be hashed in my ASP.NET Webforms.
How do I then enter the hashed password into the database via a string?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName, #surname, #email, #username, #passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.ToString("passwordHash");
cmd.ExecuteNonQuery();
I knew I couldn't use .AddWithValue and thought of .ToString may have been the one to use.
I am new to C#.
Thanks.
Does this work?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
{
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName,#surname,#email,#username,#passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.AddWithValue("passwordHash", passwordHash);
cmd.ExecuteNonQuery();

Checking if user exists in MySQL database fails

Not sure why the following code gives me an exception. I'm trying to check if a username exists in a MySQL database, if not then I want to create a user. If I run either query by itself then it works ok but not together.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
string sql1 = String.Format("SELECT Username FROM Users WHERE Username = \"{0}\"", username);
MySqlCommand cmd1 = new MySqlCommand(sql1, cnn);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
string sql = String.Format("INSERT INTO Users(Username, Password) VALUES(\"{0}\", \"{1}\")", username, password);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
First, MySQL uses single quotes. This means your query would be:
string.format("SELECT Username FROM Users WHERE Username = '{0}' LIMIT 1", Username);
However, this is very vulnerable with SQL injection. Here's a code to use MySQL Parameters to prevent it.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
cmd1.Parameters.AddWithValue("#username", username);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Users(Username, Password) VALUES(#username, #password)", cnn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
Could you try this?
I got it working by changing the first query from:
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
to
MySqlCommand cmd1 = new MySqlCommand("SELECT COUNT(UserID) FROM Users WHERE Username = #username", cnn);
int valid = int.Parse(cmd.ExecuteScalar().ToString());
Thanks for the help.

Update table values using cmd.Parameters.AddWithValue not working

I have to update some values in table row if UserId = Session["username"]
but its showing error:
ExecuteNonQuery: Connection property has not been initialized.
can any one know what i am doing wrong here a Session["username"] have its value i have checked.
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (#FirstName, #LastName, #Password, #EmaildId, #UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
You need to tell the SqlCommand-object which connection to use, change this line
var cmd = new SqlCommand(qry, conn7);
Two Problems
In SQLCOMMAND you should specify querystring,connection
Your update query syntax is wrong
..try below
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=#FirstName,LastName=#LastName,Password=#Password,
EmaildId=#EmaildId,UserId=#UserId WHERE UserId=#UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
Use Parameters for all you input, don't concatenate strings in queries.
As for your error, you need to specify the connection that the command needs to use:
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = #FirstName, LastName = #LastName,"
+ " Password = #Password, EmaildId = #EmaildId WHERE UserId = #UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing

Nothing happens after an update command for sql in C#. Where is my mistake?

I'm trying to make a function to password reset. I have a database with 3 columns: Username, Password, Email.
I want to update the password for a specific email address.
I used the following code:
try
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Server=WIN2CNG9\\SQLEXPRESS;Database=OOPII_Project;Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Users SET Password = #pass WHERE Email = #email";
cmd.Parameters.AddWithValue("#pass", md5Kod);
cmd.Parameters.AddWithValue("#email", Email);
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Ok");
connection.Close();
this.Close();
}
But nothing happens in my database.
I tried also to make a simple insert command:
cmd.CommandText = "INSERT INTO Users (Username, Password, Email) VALUES ('a', 'b', 'c')";
Here the same result, nothing happens.
Where is my mistake?
Thank you!
This line
cmd.Parameters.AddWithValue("#fn", Email);
should change to this
cmd.Parameters.AddWithValue("#email", Email);
You have two parameters, #pass and #email. While for the first one you pass a value, for the second you don't.

Asp.net Getting values from access database

I am trying to get all the details of a User in an Access database. But i cant seem to save each columns value to a label. Here is the code i am using.
Also UserId has a value assigned to it already
string connString = (#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=DataDirectory|HorseDB.mdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId ";
cmd.Parameters.AddWithValue("#UserId", UserId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
accountUserIdLabel.Text = dbReader.GetValue(0).ToString();
//Will add other labels once this works
}
dbReader.Close();
conn.Close();

Categories

Resources