簡體   English   中英

錯誤“'/'附近的語法不正確”

[英]Error "Incorrect Syntax Near '/'

我的C#出現問題,每當我嘗試將新數據保存在來自串行comm的數據庫中時,都會出現錯誤並說

'/'附近的語法不正確

我嘗試了每個人提出的所有建議,但都沒有停止。在這里,這是一段代碼。

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SqlConnection cn = new SqlConnection(global::test_new.Properties.Settings.Default.Database3ConnectionString);
    try
    {
        string sql = "INSERT INTO PowerData (Date/Time,Power(W)) values(" + this.powerTextBox.Text + ",'" + this.powerTextBox.Text + "'");

        SqlCommand exeSql = new SqlCommand(sql, cn);
        cn.Open();
        exeSql.ExecuteNonQuery();

        this.powerDataTableAdapter.Fill(this.database3DataSet.PowerData);

    }
    catch (Exception ex)
    {

    }
}

您需要在表和列名稱中轉義特殊字符,例如/

INSERT INTO PowerData ([Date/Time], Power(W)) values ...

在MySQL中,請使用反引號進行轉義,在MSSQL中,請使用方括號。

您在那里有一些瘋狂的列名。 如果要在這樣的列名稱中包括特殊字符,則必須在SQL中將它們包裝在方括號中,例如[Date/Time] 一個更好的主意是不要首先使用此類字符。

語法應如下所示,用特殊字符轉義所有列

INSERT INTO PowerData
([Date/Time], [Power(W)])
VALUES
(GETDATE(), 'test1')

DEMO

首先,“ this.powerTextBox.Text”-我猜這兩個變量的值不應相同

將您的代碼更改為此:

DateTime dt = DateTime.Parse(this.powerTextBox.Text); 
string PowerW = this.powerTextBox.Text;
string sql = "INSERT INTO PowerData ([Date/Time],[Power(W)]) values(@val1, @val2);"

    SqlCommand exeSql = new SqlCommand(sql, cn);
exeSql.Parameters.AddWithValue("@val1",  dt);
exeSql.Parameters.AddWithValue("@val2",  PowerW);
    cn.Open();
exeSql.ExecuteNonQuery();

暫無
暫無

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

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