每当我在C#上运行以下事件时,我都会在OleDbException was unhandled, characters found after end of SQL statement
行收到以下错误消息 - int affectedRows = (int)command.ExecuteNonQuery();
。知道如何解决它吗?
private void save_btn_Click(object sender, EventArgs e)
{
if (pgpText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: PGP");
}
else if (teamText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: Team");
}
else
{
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET PGP=pgp,Team=team WHERE pgp=pgp; SELECT @@ROWCOUNT;";
conn.Open();
int affectedRows = (int)command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (PGP,Team) VALUES (pgp,team)";
command.ExecuteNonQuery();
}
}
}
}
答案 0 :(得分:4)
我怀疑您实际尝试使用参数 - 请注意,C#中的pgp
和team
变量未被使用在你的代码中。我怀疑你想要的东西:
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET Team=? WHERE PGP=?";
command.Parameters.Add("team", OleDbType.VarChar).Value = team;
command.Parameters.Add("pgp", OleDbType.VarChar).Value = pgp;
conn.Open();
int affectedRows = (int) command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (Team, PGP) VALUES (?, ?)";
// Parameters as before
command.ExecuteNonQuery();
}
}
请注意,我已从您的更新中删除了“SELECT @@ ROWCOUNT”部分 - 这是不需要的,因为ExecuteNonQuery
会返回受影响的行数。
其他几点说明:
VALUES (@pgp, @team)
然后使用参数名称...但.NET中的OLE DB提供程序不支持这些。