con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO user(Firstname,Lastname,Email,Pass,Type)
values(@first,@last,@email,@pass,@type)",con);
cmd.Parameters.Add("@first",SqlDbType.NVarChar).Value = txtfirst.Text;
cmd.Parameters.Add("@last",SqlDbType.NVarChar).Value = txtlast.Text;
cmd.Parameters.Add("@email",SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.Add("@pass",SqlDbType.NVarChar).Value = txtpass.Text;
cmd.Parameters.Add("@type",SqlDbType.NVarChar).Value = "customer";
cmd.ExecuteNonQuery();
con.Close();
我的语法有什么问题,它说“关键字'user'附近的语法不正确。”
答案 0 :(得分:9)
您应该使用分隔标识符
来转义表名user
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(@first,@last,@email,@pass,@type)",con);
更新1
通过
来折射你的代码using
语句正确处理对象Try-Catch
块来正确处理异常代码段:
string _connStr = "connectionString here";
string _query = "INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values (@first,@last,@email,@pass,@type)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("@first", txtfirst.Text);
comm.Parameters.AddWithValue("@last", txtlast.Text);
comm.Parameters.AddWithValue("@email", txtemail.Text);
comm.Parameters.AddWithValue("@pass", txtpass.Text);
comm.Parameters.AddWithValue("@type", "customer");
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(SqlException ex)
{
// other codes here
// do something with the exception
// don't swallow it.
}
}
}
答案 1 :(得分:1)
USER
是SQL Server上的reserved keyword。
您应该使用括号[]
之类的表格名称
INSERT INTO [user]
你可以试试;
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(@first,@last,@email,@pass,@type)",con);
cmd.Parameters.AddWithValue("@first", txtfirst.Text);
cmd.Parameters.AddWithValue("@last", txtlast.Text);
cmd.Parameters.AddWithValue("@email", txtemail.Text);
cmd.Parameters.AddWithValue("@pass", txtpass.Text);
cmd.Parameters.AddWithValue("@type", "customer");
cmd.ExecuteNonQuery();
con.Close();
并且像@JW所说的那样,在try-catch语句中使用它们总是一种很好的方法。