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();
Related
I have this code, and when I execute it, it doesn't work
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = 'username', pass = '#password' where IDetudient='#ID ' ", con);
con.Open();
cmd.Parameters.AddWithValue("#username", text_name.Text);
cmd.Parameters.AddWithValue("#password",Convert.ToDecimal( textBox1.Text));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt64( text_id.Text));
cmd.ExecuteNonQuery();
con.Close();
Try this way:
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient=#ID", con);
I had the same issue. The thing is, in the query you just pass the name of the parameter.
Your sql command't test would be:
var cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient = #ID ", con);
Also, you will need to validate if conversion from string to int64 if fails or not.
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
I created some simple code, but it looks like something is working wrong with my Insert I get error about "where". What did I do wrong?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) where Login =#Login and Password=#Password and Type=#UserType ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
SQL Insert Into statement is
INSERT INTO Table_Name ( Col1, Col2, Col3)
VALUES ( Val1, Val2, Val3);
I think,
insert into dbo.UserInfo (Login, Password, UserType, ID)
where Login =#Login and Password=#Password and Type=#UserType "
try to change the code to this.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) " +
" VALUES(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
INSERT statements don't have WHERE clauses, UPDATE statements do.
You would only use a WHERE clause if there was an actual select statement.
Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
SELECT Login, Password, UserType, ID
FROM Table
where Login =#Login
and Password=#Password
and Type=#UserType
Otherwise you just use the values. Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
VALUES (#Login,#Password,#UserType, #ID)
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Your query should probably be
"insert into dbo.UserInfo (Login, Password, UserType, ID) values (#Login, #Password, #UserType)"
I am not sure why you are using where while inserting single record to table. Below is the proper code to insert
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO UserInfo(Login, Password, UserType) VALUES(#Login,#Password,#Type)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#Login", TextBox1.Text);
cmd.Parameters.AddWithValue("#Password", TextBox2.Text + ".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
Please, follow below syntex:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
=============
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType) values(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Only check your Insert Syntax you will get the answer :
"insert into dbo.xyz(Login, Password, ID) values (#Login, #Password)"
dbo:xyz = your table name
I have 2 tables:
RESERVATION
ID, DATE, TIME, TABLE
CLIENT
ID_CLIENT, FNAME, LNAME, EMAIL, PHONE, FK_RESERVATION
I have working INSERT statement for Reservation Table-
string insertSql = "INSERT INTO Rezervacija (date,time,table) VALUES (#date,#time,#table);
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
But the problem comes with INSERT INTO Client Table Foreign Key.
Can anyone help me how to insert data into two related tables.
You'll need to modify your query to get the ID of the row that you just inserted.
string insertSql = "INSERT INTO Rezervacija (date,time,table) OUTPUT INSERTED.Id VALUES (#date,#time,#table);"
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
var **reservationId** = (int)cmd.ExecuteScalar()
string insertSql2 = "INSERT INTO CLIENT (ID_CLIENT,FNAME,LNAME,EMAIL,PHONE,FK_RESERVATION) VALUES (#clientId, #fname, #lname, #email, #phone, #reservation"
SqlCommand cmd2 = new SqlCommand(insertSql2, con);
cmd.Parameters.AddWithValue("#clientId", clientId);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#reservation", **reservationId**);
This will allow you use the Inserted.Id in your second query as you've returned the output to a variable.
I have an ASP.Net website which is connected to an SQL Server. In a previous project (VB) I used the following code to write to my database:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
Dim insertSql As String = "INSERT INTO tblProfile(UserID, UserName, Title, FirstName, LastName, MiddleName, DateofBirth, Gender, HomePhoneNumber, MobilePhoneNumber, Address, StreetName, StreetType, Suburb, PostCode, State, Country) VALUES(#UserID, #UserName, #Title, #FirstName, #LastName, #MiddleName, #DateofBirth, #Gender, #HomePhoneNumber, #MobilePhoneNumber, #Address, #StreetName, #StreetType, #Suburb, #PostCode, #State, #Country)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#UserID", newUserGuid)
myCommand.Parameters.AddWithValue("#UserName", newUserName)
myCommand.Parameters.AddWithValue("#Title", Title.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#FirstName", FirstName.Text)
myCommand.Parameters.AddWithValue("#LastName", LastName.Text)
If MiddleNames.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MiddleName", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MiddleName", MiddleNames.Text)
End If
DateofBirth.Text = YearofBirth.Text + "-" + MonthofBirth.Text + "-" + DayofBirth.Text
myCommand.Parameters.AddWithValue("#DateofBirth", DateofBirth.Text)
myCommand.Parameters.AddWithValue("#Gender", Gender.SelectedItem.Text)
If HomePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#HomePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#HomePhoneNumber", HomePhoneNumber.Text)
End If
If MobilePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", MobilePhoneNumber.Text)
End If
myCommand.Parameters.AddWithValue("#Address", AddressNumber.Text)
myCommand.Parameters.AddWithValue("#StreetName", StreetName.Text)
myCommand.Parameters.AddWithValue("#StreetType", StreetType.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Suburb", Suburb.Text)
myCommand.Parameters.AddWithValue("#PostCode", Postcode.Text)
myCommand.Parameters.AddWithValue("#State", State.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Country", Country.SelectedItem.Text)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
I've now changed to C#, and am having problems altering this code. So far I have:
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
String insertSql = "INSERT INTO tbl_UserProfiles VALUES(#UserID, #FirstName, #LastName, #YearOfBirth, #Country)";
SqlCommand myCommand = new SqlCommand(insertSql, connectionString);
myCommand.Parameters.AddWithValue("#UserID", newUserGuid);
myCommand.Parameters.AddWithValue("#FirstName", FirstNameTB.Text);
myCommand.Parameters.AddWithValue("#LastName", LastNameTB.Text);
myCommand.Parameters.AddWithValue("#YearOfBirth", YearDDL.SelectedItem.Text);
myCommand.Parameters.AddWithValue("#Country", CountryDDL.SelectedItem.Text);
try
{
connectionString.Open();
myCommand.ExecuteNonQuery();
}
finally
{
connectionString.Close();
}
Which I've tried to create after looking at a few tutorial sites and my own previous code. But, I believe I'm doing something wrong here:
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
as I get the squiggly red underline.
try this....
Use SqlConnection
Using myConnection As New SqlConnection(connectionString) you did not convert this line to C#
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
SqlConnection con = new Sqlconnection(connectionString);
String insertSql = "INSERT INTO tbl_UserProfiles VALUES(#UserID, #FirstName, #LastName, #YearOfBirth, #Country)";
SqlCommand myCommand = new SqlCommand(insertSql, con);
myCommand.Parameters.AddWithValue("#UserID", newUserGuid);
myCommand.Parameters.AddWithValue("#FirstName", FirstNameTB.Text);
myCommand.Parameters.AddWithValue("#LastName", LastNameTB.Text);
myCommand.Parameters.AddWithValue("#YearOfBirth", YearDDL.SelectedItem.Text);
myCommand.Parameters.AddWithValue("#Country", CountryDDL.SelectedItem.Text);
try
{
con.Open();
myCommand.ExecuteNonQuery();
}
finally
{
con.Close();
}
It looks like you are trying to Open() a connection string :)
Translate
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
To
using (var myConnection = new SqlConnection(connectionString))
using (var myCommand = new SqlCommand(insertSql, myConnection))
{
myConnection.Open();
...
myCommand.ExecuteNonQuery();
}
using in C# on your SqlConnection and SqlCommand will guarantee that Dispose() is called on both objects, irrespective of whether success or fail (and close connections, cleanup etc)
Make sure you have
using System.Configuration
at the top of the file. Also does your web.config file contain a configuration > configSections > configSections section?