【问题标题】:Sql Exception Unhandled Incorrect syntax near '='?Sql Exception Unhandled '=' 附近的语法不正确?
【发布时间】:2013-03-03 13:33:06
【问题描述】:

这是我的搜索按钮:

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;
    }

这是我上面的代码,当我搜索数据库时出现错误输入主号码意味着..谁能帮助我..

【问题讨论】:

  • 打印出 newCmd 的内容以查看您尝试执行的语句。比请将此添加到您的问题中。
  • RegNo = null ???或“”???
  • 啊,给你介绍Little Bobby Tables

标签: c# sql exception


【解决方案1】:

首先你应该在你的 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 以查看最终查询是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多