我的查詢是完美的(我已經在SQL Server Management Studio中對其進行了驗證)。我的代碼是完美的,還是我得到這個語法錯誤:Command.ExecuteNonQuery();錯誤:'='附近的語法不正確
Incorrect syntax near '='. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.
public partial class Temporaryche : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ddlTDept.Items.Clear();
ddlTBranch.Items.Clear();
string connectionString = GlobalVariables.databasePath;
SqlConnection sqlCon = new SqlConnection(connectionString);
string query = "select fac.fac_name, dp.dp_name, br.br_name from STUDENT s, DIVISON dv, BRANCH br, DEPT dp, FACULTY fac, CLASS cls, DEGREE dg where dg.dg_id = cls.dg_id and cls.cls_id = s.cls_id and fac.fac_id = dp.fac_id and dp.dp_id = br.dp_id and br.br_id = dv.br_id and s.dv_id = dv.dv_id and s.prn_no = " + txtSearch.Text;
sqlCon.Open();
SqlCommand cmd = new SqlCommand(query, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
string facultyName = reader.GetValue(0).ToString();
string deptName = reader.GetValue(1).ToString();
string branchName = reader.GetValue(2).ToString();
ddlTFaculty.SelectedValue = facultyName;
query = "select dp_name from DEPT where fac_id=(select fac_id where fac_name='" + facultyName + "')";
cmd = new SqlCommand(query, sqlCon);
reader = cmd.ExecuteReader();
ddlTDept.Items.Clear();
while (reader.Read())
{
ddlTDept.Items.Add(reader.GetValue(0).ToString());
}
ddlTDept.SelectedValue = deptName;
sqlCon.Close();
}
}
我的錯誤是這樣的: 附近有語法錯誤「=」。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。 異常詳細信息:System.Data.SqlClient.SqlException:'='附近的語法不正確。 – AlexR
您應該使用SQL參數,而不是將facultyName內聯到SQL查詢中。否則,你很容易受到SQL注入攻擊。 https://開頭XKCD。com/327/ –
[壞習慣踢:使用舊式聯接](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old- style-joins.aspx) - 在ANSI - ** 92 ** SQL標準(**超過20年)中,舊式*逗號分隔的表*樣式列表已替換爲* proper * ANSI'JOIN'語法**前),其使用是不鼓勵 –