It is good practice not to use concatenated SQL queries as it opens up for injection of malicious commands, especially when using user input directly.
You should use parameters instead. See the code example below.
It is also good practice to use the
using
clause as it will close the connection automatically when leaving the scope.
using
works like
try-catch-finally
, where you close the connection in the finally clause.
(In your original code, you never close the connection if you have an exception)
In this case you should use
ExecuteNonQuery
as you do an INSERT and might not get a reply from the DB.
string cs = ConfigurationManager.ConnectionStrings["winningways"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(cs))
{
connection.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandText = "insert into winningways.staff (name, address, mobileNumber, position, username, password) values (@name, @address, @mobileNumber, @position, @username, @password)";
command.Parameters.Add("@name", empname.Text);
command.Parameters.Add("@address", empadd.Text);
command.Parameters.Add("@mobileNumber", empnum.Text);
command.Parameters.Add("@position", emppos.Text);
command.Parameters.Add("@username", empname.Text);
command.Parameters.Add("@password", password);
command.ExecuteNonQuery();
}