[英]SQL query in C# (System.Data.OleDb.OleDbException: 'Syntax error (missing operator) in query expression)
[英]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 statement
在int 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();
}
}
}
}
我懷疑你實際上是試圖用參數-注意,你的pgp
和team
在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提供程序不支持這些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.