在C#上运行SQL查询时出错 - 未处理OleDbException,在SQL语句结束后找到字符

时间:2013-12-29 18:09:41

标签: c# sql

每当我在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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:4)

我怀疑您实际尝试使用参数 - 请注意,C#中的pgpteam变量未被使用在你的代码中。我怀疑你想要的东西:

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提供程序不支持这些。
  • 使用SQL的字符串连接作为另一个答案(可能在您阅读本文时已删除)建议 - 这为SQL Injection attacks和转换问题铺平了道路。 (这很麻烦。)