Hamood Shi1707
Hamood Shi1707

Reputation: 71

Load data from SQL Server database to C#

I get this error:

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.

when I run the program; it said the error near to table!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string SOURCE = @"Data Source=DESKTOP-K39PU4T\SQLEXPRESS;Initial Catalog=Mohamed;Integrated Security=True";

            SqlConnection CON = new SqlConnection(SOURCE);
            CON.Open();

            MessageBox.Show("DB Connected");

            string SqlSelectQuery = " Select*From Table Where ID ="+ int.Parse(textBox1.Text);

            SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                textBox2.Text = (dr["Name"].ToString());
                textBox3.Text = (dr["Surname"].ToString());
                textBox4.Text = (dr["Lastname"].ToString());
            }
            else
            {
                textBox1.Text = "";
                textBox2.Text = "";
                textBox3.Text = "";
                textBox4.Text = "";

                MessageBox.Show("No Record Found Please Enter Correct Id");
            }

            CON.Close();
        }
    }
}

I want to load the data from SQL Server to ASP.NET in Visual Studio

Upvotes: 0

Views: 4915

Answers (2)

Damith
Damith

Reputation: 63065

Table is key word, if you have table named "Table" you may need to use [Table] for escape keyword in the SQL string, otherwise give the correct table name instead of Table. also you better use parameters instead of concatenating string as sql statement.

string SqlSelectQuery = "Select * From [Table] Where ID =@ID";
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
cmd.Parameters.AddWithValue("@ID", int.Parse(textBox1.Text));

Upvotes: 1

Waqas
Waqas

Reputation: 56

What is the table name from which you want to get data?

if its name is Table then replace " Select*From Table Where ID =" with " Select * From \"Table\" Where ID =" otherwise replace Table with actual table name

Upvotes: 0

Related Questions