0

i'm building a web application (asp.net & c#), i want to connect it with db(which i'm building ) , and i looking for tutorial \ book about connecting with db and doing it safely (avoiding sql injections). my queries are very simple and not complex.

i read a little bit about stored procedures,prepared statements,LiNQ it's all really confusing me.

can someone point me where to read how to do it?

0

2 Answers 2

3

Accessing a database in ASP.NET is no different than accessing a database in any .NET application simply because ASP.NET is a .NET application. And the way to access a relational database in .NET is to use ADO.NET.

As long as you are using parametrized queries you are safe against SQL injection. Let's take an example with SQL Server:

string firstname = "John";
using (var conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT lastname FROM mytable WHERE firstname = @firstname;";
    cmd.Parameters.AddWithValue("@firstname", firstname);
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            string lastName = reader.GetString(0);
            // do something with the value
        }
    }
}

Now compare with the following (bad code):

string firstname = "John";
using (var conn = new SqlConnection("Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT lastname FROM mytable WHERE firstname = '" + firstname + "';";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            string lastName = reader.GetString(0);
            // do something with the value
        }
    }
}

This second example is bad and vulnerable to SQL injection. So basically everytime you use the + operator when building your query string you are doing it wrong.

And once you get tired of writing all those SQL queries you may consider using an ORM. The one that's shipped with .NET is called ADO.NET Entity Framework.

0

That's a pretty broad question. I would recommend you spend some time using Google to get a better understanding of ADO.NET as a starting point.

Connecting to Databases in ASP.NET

ASP.NET Data Access Tutorials

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.