关键字'where'附近语法错误
本文关键字:语法 错误 where 关键字 | 更新日期: 2023-09-27 18:05:57
public bool location()
{
string OUI = "OUI";
SqlConnection con = new SqlConnection(@"Data Source=WIN-218NC1F1FE2'SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string v = Convert.ToString(maxId);
//correct
SqlCommand q = new SqlCommand("insert into reservation(location) values('" + OUI + "') where id_reservation ='"+ maxId + "'", con);
SqlDataReader da = q.ExecuteReader();
return true ;
}
问题出现在命令where:关键字'where'附近语法错误。帮助! !
在insert
语句中不能有where
子句。这就是它的全部。如果需要插入,请删除where
子句。如果您需要更新符合条件的记录,不要使用insert
,而是使用update
。
同样,如果您对查询结果不感兴趣,不要使用ExecuteReader
,而要使用ExecuteNonQuery
。
Thorsten的答案是明确和完整的,我只是为每个情况添加代码:
SqlConnection con = new SqlConnection(@"Data Source=WIN-218NC1F1FE2'SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string ID=maxId.TOString();
//correct
/////INSERT
SqlCommand q = new SqlCommand("insert into reservation(location) values(@location,@ID)", con);
q.Parameters.AddWithValue( "@location",OUI);
q.Parameters.AddWithValue("@ID",ID);
q.ExecuteNonQuery();
return true ;
////////UPDATE
SqlCommand q = new SqlCommand("update reservation set location=@location where id_reservation =@ID", con);
q.Parameters.AddWithValue( "@location",OUI);
q.Parameters.AddWithValue("@ID",ID);
q.ExecuteNonQuery();
return true ;