简体   繁体   中英

C# SQL Syntax Error

Can anyone tell me why when I try to add a field into this SQL Server database I get the error

Incorrect Syntax near the keyword 'Table'.

Code:

{
    // TODO: This line of code loads data into the 'tBoxDataSet.Table' table. You can move, or remove it, as needed.
    this.tableTableAdapter.Fill(this.tBoxDataSet.Table);
}

private void button1_Click(object sender, EventArgs e)
{
         SqlConnection cn = new SqlConnection(global::TicketBox.Properties.Settings.Default.TBoxConnectionString);
        try
        {
            using (SqlConnection connect = new SqlConnection(global::TicketBox.Properties.Settings.Default.TBoxConnectionString))
            using (SqlCommand runsql = new SqlCommand(@"INSERT INTO Table (Event_ID,Artist,Venue,Date,Time,Tickets) values(@EventID,@Artist, @Venue, @Date, @Time,@Tickets)", connect))
            {
                runsql.Parameters.Add("@EventID", SqlDbType.Int).Value = textBox1.Text;
                runsql.Parameters.Add("@Artist", SqlDbType.VarChar).Value = textBox2.Text;
                runsql.Parameters.Add("@Venue", SqlDbType.VarChar).Value = textBox3.Text;
                runsql.Parameters.Add("@Date", SqlDbType.Date).Value = textBox4.Text;
                runsql.Parameters.Add("@Time", SqlDbType.Time).Value = textBox5.Text;
                runsql.Parameters.Add("@Tickets", SqlDbType.Int).Value = textBox6.Text;
                connect.Open();
                runsql.ExecuteNonQuery();
            }

            MessageBox.Show("Event Added", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.tableTableAdapter.Fill(this.tBoxDataSet.Table);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            cn.Close();
        }

Table and Time are reserved keyword in T-SQL. You need to use them with square brackets like [Table] and [Time] .

As a best practice, change them to non-reserved words.

Also Date can be a reserved keyword in future releases of SQL Server. You might need to use it with square brackets as well.

if your table name is TABLE, then.. that is a keyword for sql...

change your query to

INSERT INTO [Table]

using [ ] will override the keyword

as Tabel is a reserved keyword , you need to use like this [table]

change the query to.

INSERT INTO [Table] (Event_ID,Artist,Venue,Date,Time,Tickets)  
values(@EventID,@Artist, @Venue, @Date, @Time,@Tickets)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM