Is this code safe from SQL injections? Why?
public void AddPlayer(string username)
{
var query = "INSERT INTO dbo.Player(Username, RegisterDate) VALUES(@Username, @RegisterDate)";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@RegisterDate", DateTime.Now);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
public DateTime GetRegisterDate(string username)
{
var query = "SELECT RegisterDate FROM dbo.Player WHERE Username = @Username";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Connection.Open();
return (DateTime)command.ExecuteScalar();
}
}
EDIT: Could injection-safe equivalent code be written using a stored procedure? If so, what the stored procedure would be like?
Yes, It looks safe.
Because it uses parameters.
You run a risk of SQL-injection when you create queries like
baseQueryText + " WHERE Username =" + TextBox.Text;
Reguarding the Edit: When you use a Stored Procedure you always use parameters so they are safe too. No special effort required, but you still could/should filter incoming data.
Yes. You are using parameterized queries, which are in general considered safe from SQL injection.
You may still want to consider filtering your inputs anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With