簡體   English   中英

在C#上運行SQL查詢時出錯-未處理OleDbException,在SQL語句結束后找到了字符

[英]Error running SQL query on C# - OleDbException was unhandled, characters found after end of SQL statement

每當我在C#上運行以下事件時,我都會收到以下錯誤消息- OleDbException was unhandled, characters found after end of SQL statementint affectedRows = (int)command.ExecuteNonQuery(); 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();
            }
        }
    }
}

我懷疑你實際上是試圖用參數-注意,你的pgpteam在C#中的變量沒有被使用在所有在你的代碼。 我懷疑您想要類似的東西:

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注入攻擊和轉換問題。 (而且很亂。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM