Sana ullah
Sana ullah

Reputation: 29

Changing the value of a label with text from a database

I have written some code to change a labels text property to a value from a database. However I am having problems. The code is as follows:

OleDbConnection Con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\attDB.accdb");
try
{
    Con.Open();
    string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID="+tID.Text+" && t_pass="+tPass.Text;
    OleDbCommand cmd = new OleDbCommand(strcom1,Con);
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
    if (reader.HasRows)
    {
        if (reader.Read())
        {
            t_Name.Visible = true;
            t_Name.Text = reader["t_Name"].ToString();
        }
    }
    else
    {
        t_Name.Text = "";   
    }
    reader.Close();
    Con.Close();
}
catch (Exception ex)
{
    MessageBox.Show("Error : " + ex);
}
finally
{
    Con.Close();
}

Upvotes: 1

Views: 1410

Answers (2)

Steve
Steve

Reputation: 216293

I think that your query string is wrong. The AND operator

string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID="+tID.Text+" AND t_pass="+tPass.Text;
                                                                     ^^^

But there are also problems with proper quoting of your string parameters. You should avoid string concatenation and build a parameterized query like this

string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID=? AND t_pass=?";
OleDbCommand cmd = new OleDbCommand(strcom1,Con);
cmd.Parameters.AddWithValue("@p1", Convert.ToInt32(tID.Text);
cmd.Parameters.AddWithValue("@p2", tPass.Text);

As you can see, now your query text is more readable and there is no more the need to add quotes around the values for the text columns because this work is passed to the framework code that knows better than you and me how to format specific datatypes. Of course there is no more space for Sql Injection

Upvotes: 2

geedubb
geedubb

Reputation: 4057

Your SQL looks wrong. Assuming both your fields t_ID and t_pass as are strings you will also need to enclose in quotes:

string strcom1 = "SELECT t_Name FROM teacher WHERE t_ID=\""+tID.Text+"\" AND t_pass=\""+tPass.Text + "\"";

It is also not a good idea to concatenate your query as it opens your code to SQL injection. Best to use SQL parameters. I know you are a beginner, but good to learn about this sooner rather than later ;)

Upvotes: 1

Related Questions