Is this SQL Injection proof? Or at least okay? I got this off online so I could really use some help. I am currently building quite a large program and I decided to add a login page if I ever felt like making it paid. Please help!
if (txt_UserName.Text == "" || txt_Password.Text == "")
{
MessageBox.Show("Please provide a Username and Password");
return;
}
try
{
// Create SqlConnection
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName = @username and Password = @password", con);
cmd.Parameters.AddWithValue("@username", txt_UserName.Text);
cmd.Parameters.AddWithValue("@password", txt_Password.Text);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
// If count is equal to 1, than show frmMain form
if (count == 1)
Your code is SQL Injection proof. For Plain SQL Query, I personally like to use Dapper ORM which is used in StackOverflow.
It is basically same, but a lot less code and returns strongly-typed value instead of DataSet.
For example,
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
}
User user;
using (IDbConnection cnn = new SqlConnection(cs))
{
user = cnn.Query<User>(
"Select UserName, Password from tbl_Login where UserName=@username and Password=@password",
new { username = txt_UserName.Text, password = txt_Password.Text })
.SingleOrDefault();
}
if (user != null)
{
// Do someting
}
FYI: It seems that you are storing Plain Password. If so, it is not a good practice. Instead, you want to store salted hashed password.