SDR
SDR

Reputation: 37

Sql Exception Unhandled Incorrect syntax near '='?

This is my Search Button :

private void btnSearch_Click(object sender, EventArgs e)
    {
        string RegNo = txtRegNo.Text;
        txtFname.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "PhoneNo");
        txtLname.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "Lname");
        txtPhoneNo.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "PhoneNo");

    }

This is my DB_Access :

public string ReturnStudentData(string Primary_key, string Table_Name, string RegNo, string Column)
    {
        string temp = "";
        if (conn.State.ToString() == "Closed")
        {
            conn.Open();
        }
        SqlCommand newCmd = conn.CreateCommand();
        newCmd.CommandType = CommandType.Text;
        newCmd.CommandText="SELECT"+Column+"FROM"+Table_Name+"WHERE"+Primary_key+"="+RegNo+"";
        SqlDataReader dr = newCmd.ExecuteReader(); **// here i got error**

        while(dr.Read())
        {
            temp = dr[Column].ToString();
        }
        dr.Close();
        conn.Close();
        return temp;
    }

This is my code above i got error while i search the DB put primary number means..can anyone help me..

Upvotes: 0

Views: 765

Answers (1)

Mortalus
Mortalus

Reputation: 10712

first of all you should add spaces to your sql command

newCmd.CommandText="SELECT "+Column+" FROM "+Table_Name+" WHERE "+Primary_key+"="+RegNo+"";

or else you would get something like that:

SELECTcolumnt1,column2FROMmyTableWHEREKey=123

instead of:

SELECT columnt1,column2 FROM myTable WHERE Key=123

secondly print the newCmd.CommandText to see what is the final query.

Upvotes: 3

Related Questions