简体   繁体   中英

C# Error of my line of code that it keep pop out Incorrect syntax near the keyword 'Table" after I run the code and inputted a value of 1

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        private const string V = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Simple;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            const string ConnectionString = V;
            SqlConnection conn1 = new SqlConnection(ConnectionString);
            conn1.Open();
            SqlCommand cmd1 = new SqlCommand("select Id, First Name, Last Name, sum from Table where id=@id", conn1);
            cmd1.Parameters.AddWithValue("Id", textBox1.Text);
            SqlDataReader reader1;
            reader1 = cmd1.ExecuteReader();
            if(reader1.Read())
            {
                textBox2.Text = reader1["First Name"].ToString();
                textBox2.Text = reader1["Last Name"].ToString();
                textBox2.Text = reader1["Sum"].ToString();
            }
            else
            {
                MessageBox.Show("no data found");
            }
            conn1.Close();

            
        }
    }
}

在此处输入图片说明

Is your column names have spaces in the database? Is it "First Name" or "FirstName" (same question for the last name)?

If it is FirstName and LastName then try this (I removed space from First Name and LastName and added brackets to the sum and Table as they are reserved words):

SqlCommand cmd1 = new SqlCommand("select Id, FirstName, LastName, [sum] from [Table] where id=@id", conn1);

If it is with space then try this:

SqlCommand cmd1 = new SqlCommand("select Id, [First Name], [Last Name], [sum] from [Table] where id=@id", conn1);

Note, it is not a good practice to use reserved names for your column names. I would recommend you to change the column names to non-reserved words.

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