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'附近的语法不正确。 帮助!!!
答案 0 :(得分:5)
where
语句中不能包含insert
子句。这就是它的全部。如果要插入,请删除where
子句。如果您需要更新符合条件的记录,请不要使用insert
,而是使用update
。
此外,如果您对查询结果不是真的感兴趣,请不要使用ExecuteReader
,而是使用ExecuteNonQuery
。
答案 1 :(得分:0)
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 ;