Sql异常未处理'='附近的语法不正确?

时间:2013-03-03 13:33:07

标签: c# sql exception

这是我的搜索按钮:

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");

    }

这是我的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;
    }

这是我的上面的代码我得到错误,而我搜索数据库把主要数字意味着..可以任何人帮助我..

1 个答案:

答案 0 :(得分:3)

首先,您应该在sql命令中添加空格

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

否则你会得到类似的东西:

SELECTcolumnt1,column2FROMmyTableWHEREKey=123

而不是:

SELECT columnt1,column2 FROM myTable WHERE Key=123

其次打印newCmd.CommandText以查看最终查询是什么。