Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a datatable is null

Tags:

c#

sql

The following code is what I've been using to retrieve user information from a sql database.

            string userName = LoginUser.UserName;
            string password = LoginUser.Password;
            string comm = "SELECT Username,Password,Clientname,Role FROM Users WHERE Username = '" + userName + "';";
            bool rememberUserName = LoginUser.RememberMeSet;

            SqlConnection conn = new SqlConnection(connstring);
            conn.Open();

            SqlCommand command = new SqlCommand(comm, conn);
            SqlDataAdapter da = new SqlDataAdapter(command);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr = dt.NewRow();
            if (dt != null)
            {
                //logic
            }

However, (dt != null) does not return false when there is no entry in the database with the username equal to LoginUser.Username. Is there a different way to check whether or not the sqlcommand is successful?

like image 428
Tony Avatar asked Sep 10 '12 20:09

Tony


2 Answers

Why not just change the statement a bit to see if the DataTable is either null or has no rows:

if(dt != null && dt.Rows.Count > 0)

Also, on a side note, you should look into Parameterized Queries as well rather than building your SQL dynamically. It will reduce the number of attack vectors for attackers trying to compromise your application.

like image 95
Justin Niessner Avatar answered Oct 11 '22 12:10

Justin Niessner


You will get an empty DataTable if no records match, so you can check on the number of records returned:

if (dt.Rows.Count > 0)

And, slightly off topic, please read the comments below your question, then Google the terms SQL Injection and Parameterized SQL statements. Try starting with this.

like image 40
driis Avatar answered Oct 11 '22 12:10

driis