I have created a simple Username and Password login form in visual studio using c# which works great I then coded it so that whatever Username and Password was entered into the two textboxes was saved as a string... Now I want to pass those strings as parameters and store them into an SQL query... Any idea how I would go about doing this?
-
Well, why don't ask google for something like "c# sql server parameterized query" first, then try to implement it according to examlples you'll found, and then (if you've stuck with something) - post your question at SO....Andrey Korneyev– Andrey Korneyev2015-10-23 09:26:51 +00:00Commented Oct 23, 2015 at 9:26
-
3There are probably more examples of C# SQL code on the internet than there is porn. It shouldn't be hard to find what you want with a simple search!musefan– musefan2015-10-23 09:28:17 +00:00Commented Oct 23, 2015 at 9:28
-
Trust me there isnt!Declan Tiff– Declan Tiff2015-10-23 09:34:24 +00:00Commented Oct 23, 2015 at 9:34
-
You'll also want to do a search on "salted hashed passwords" as well - you should not be storing passwords plain-text :)racraman– racraman2015-10-23 09:39:09 +00:00Commented Oct 23, 2015 at 9:39
-
Oh no don't worry the passwords aren't going to be stored in plain text, I've created a code which applies an encryption key to the password to completely mask the originalDeclan Tiff– Declan Tiff2015-10-23 09:43:26 +00:00Commented Oct 23, 2015 at 9:43
1 Answer
I would highly recommend NOT to store passwords as plain text. Instead look into hashed password methods.
Firstly you will need to specify a connection string. This can be done in the config file as:
<connectionStrings>
<add name="myConnectionString" connectionString="server=ServerAddress;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Now you want to read the connection string from your config file and you can do that in your C# code as:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I'm assuming you'll be inserting records. If you are going to update records, then you will need to change the query. For inserting records:
string myQuery = "INSERT INTO MyTable (UserNameColumn,PasswordColumn) VALUES (@UserName, @Password)";
Finally to execute the query and pass our parameters we can do
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(myQuery, connection))
{
cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = UserNameTextBox.Text;
cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = PasswordTextBox.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
}
Dont forget to include the namespace using System.Configuration;
9 Comments
SqlDbType.NVarChar.