0

这是我的搜索按钮:

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

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

4

1 回答 1

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 以查看最终查询是什么。

于 2013-03-03T13:40:50.143 回答