我的insert语句出现语法错误,但我找不到错误。
这是我的方法
String sql = "insert into receivers (receiver_id, receiver_name, salary, team, forty_yard_dash, position, offense) " +
"values" +
"(@id, @name, @salary, @team, @forty, @position, @offense)";
com = new OleDbCommand(sql, con);
com.Parameters.AddWithValue("@id", rec.id);
com.Parameters.AddWithValue("@name", rec.name);
com.Parameters.AddWithValue("@salary", rec.salary);
com.Parameters.AddWithValue("@team", rec.team);
com.Parameters.AddWithValue("@forty", rec.fortyYardDash);
com.Parameters.AddWithValue("@offense", rec.offenseDefense);
con.Open();
com.ExecuteNonQuery();
con.Close();
我的数据库如下所示:
receiver_id号码
姓名文本
工资号码
团队文字
forty_yard_dash号码
职位文本
进攻是/否
任何帮助将不胜感激!
答案 0 :(得分:1)
King King已在评论中指出:
您需要添加position
String sql = "insert into receivers (receiver_id, receiver_name, salary, team, forty_yard_dash, position, offense) " +
"values" +
"(@id, @name, @salary, @team, @forty, @position, @offense)";
com = new OleDbCommand(sql, con);
com.Parameters.AddWithValue("@id", rec.id);
com.Parameters.AddWithValue("@name", rec.name);
com.Parameters.AddWithValue("@salary", rec.salary);
com.Parameters.AddWithValue("@team", rec.team);
com.Parameters.AddWithValue("@forty", rec.fortyYardDash);
//new --> I am assuming the value for position comes from rec.position; change to correct source
com.Parameters.AddWithValue("@position", rec.position);
com.Parameters.AddWithValue("@offense", rec.offenseDefense);
con.Open();
com.ExecuteNonQuery();
con.Close();
如果你没有告诉我们任何其他错误,这应该可以解决问题;)
答案 1 :(得分:1)
除了.Parameters.AddWithValue
缺少position
语句之外,另一个问题是position
在Access SQL中是reserved word,必须用方括号括起来CommandText中。我刚刚尝试了以下内容,它对我有用:
using (var con = new OleDbConnection())
{
con.ConnectionString = myConnectionString;
con.Open();
using (var com = new OleDbCommand())
{
int rec_id = 1; //
string rec_name = "Bubba"; //
int rec_salary = 2000000; //
string rec_team = "Springfield Atoms"; // test data
int rec_fortyYardDash = 99; //
string rec_position = "linebacker"; //
bool rec_offense = false; //
string sql =
"INSERT INTO receivers (" +
"receiver_id, " +
"receiver_name, " +
"salary, " +
"team, " +
"forty_yard_dash, " +
"[position], " +
"offense " +
") VALUES (?,?,?,?,?,?,?)";
com.Connection = con;
com.CommandText = sql;
com.Parameters.AddWithValue("?", rec_id);
com.Parameters.AddWithValue("?", rec_name);
com.Parameters.AddWithValue("?", rec_salary);
com.Parameters.AddWithValue("?", rec_team);
com.Parameters.AddWithValue("?", rec_fortyYardDash);
com.Parameters.AddWithValue("?", rec_position);
com.Parameters.AddWithValue("?", rec_offense);
com.ExecuteNonQuery();
}
con.Close();
}