[c#] Invalid column name sql error

I am trying to enter data into my database, but it is giving me the following error:

Invalid column name

Here's my code

string connectionString = "Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=AddressBook;Server=Bilal-PC";

using (SqlConnection connection = new SqlConnection(connectionString))
{
  SqlCommand cmd = new SqlCommand();

  cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";
  cmd.CommandType = CommandType.Text;
  cmd.Connection = connection;

  connection.Open();
  cmd.ExecuteNonQuery();
}

This question is related to c# sql-server database

The answer is


con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Yna Maningding-Dula\Documents\Visual Studio 2010\Projects\LuxuryHotel\LuxuryHotel\ClientsRecords.mdf;Integrated Security=True;User Instance=True");
        con.Open();
        cmd = new SqlCommand("INSERT INTO ClientData ([Last Name], [First Name], [Middle Name], Address, [Email Address], [Contact Number], Nationality, [Arrival Date], [Check-out Date], [Room Type], [Daily Rate], [No of Guests], [No of Rooms]) VALUES (@[Last Name], @[First Name], @[Middle Name], @Address, @[Email Address], @[Contact Number], @Nationality, @[Arrival Date], @[Check-out Date], @[Room Type], @[Daily Rate], @[No of Guests], @[No of Rooms]", con);
        cmd.Parameters.Add("@[Last Name]", txtLName.Text);
        cmd.Parameters.Add("@[First Name]", txtFName.Text);
        cmd.Parameters.Add("@[Middle Name]", txtMName.Text);
        cmd.Parameters.Add("@Address", txtAdd.Text);
        cmd.Parameters.Add("@[Email Address]", txtEmail.Text);
        cmd.Parameters.Add("@[Contact Number]", txtNumber.Text);
        cmd.Parameters.Add("@Nationality", txtNational.Text);
        cmd.Parameters.Add("@[Arrival Date]", txtArrive.Text);
        cmd.Parameters.Add("@[Check-out Date]", txtOut.Text);
        cmd.Parameters.Add("@[Room Type]", txtType.Text);
        cmd.Parameters.Add("@[Daily Rate]", txtRate.Text);
        cmd.Parameters.Add("@[No of Guests]", txtGuest.Text);
        cmd.Parameters.Add("@[No of Rooms]", txtRoom.Text);
        cmd.ExecuteNonQuery();

You problem is that your string are unquoted. Which mean that they are interpreted by your database engine as a column name.

You need to create parameters in order to pass your value to the query.

 cmd.CommandText = "INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address);";
 cmd.Parameters.AddWithValue("@Name", txtName.Text);
 cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
 cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

Your issue seems to be the Name keyword. Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.


You should never write code that concatenates SQL and parameters as string - this opens up your code to SQL injection which is a really serious security problem.

Use bind params - for a nice howto see here...


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=WKS09\SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
            SqlCommand insert = new SqlCommand("insert into dbo.StudentRegistration(ID, Name,Age,DateOfBirth,Email,Comment) values(@ID, @Name,@Age,@DateOfBirth,@mail,@comment)", conn);
            insert.Parameters.AddWithValue("@ID", textBox1.Text);
            insert.Parameters.AddWithValue("@Name", textBox2.Text);
            insert.Parameters.AddWithValue("@Age", textBox3.Text);
            insert.Parameters.AddWithValue("@DateOfBirth", textBox4.Text);
            insert.Parameters.AddWithValue("@mail", textBox5.Text);
            insert.Parameters.AddWithValue("@comment", textBox6.Text);

            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("ID Cannot be Null");
                return;
            }
            else if (textBox2.Text == string.Empty)
            {
                MessageBox.Show("Name Cannot be Null");
                return;
            }


            try
            {
                conn.Open();
                insert.ExecuteNonQuery();
                MessageBox.Show("Register done !");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message);
                conn.Close();
            }
        }

        private void btnRetrive_Click(object sender, RoutedEventArgs e)
        {
            bool temp = false;
            SqlConnection con = new SqlConnection("server=WKS09\\SQLEXPRESS;database=StudentManagementSystem;Trusted_Connection=True");
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from dbo.StudentRegistration where ID = '" + textBox1.Text.Trim() + "'", con);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                textBox2.Text = dr.GetString(1);
                textBox3.Text = dr.GetInt32(2).ToString(); 
                textBox4.Text = dr.GetDateTime(3).ToString();
                textBox5.Text = dr.GetString(4);
                textBox6.Text = dr.GetString(5);
                temp = true;
            }
            if (temp == false)
                MessageBox.Show("not found");
            con.Close();
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection connection = new SqlConnection("Data Source=WKS09\\SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
            string sqlStatement = "DELETE FROM dbo.StudentRegistration WHERE ID = @ID";
            try
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand(sqlStatement, connection);
                cmd.Parameters.AddWithValue("@ID", textBox1.Text);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Done");
            }
            finally
            {
                Clear();
                connection.Close();
            }
        }

        public void Clear()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
        }
    }
}

first create database name "School" than create table "students" with following columns 1. id 2. name 3. address

now open visual studio and create connection:

namespace school
{
    public partial class Form1 : Form
    {
        SqlConnection scon;


        public Form1()
        {

            InitializeComponent();

            scon = new SqlConnection("Data Source = ABC-PC; trusted_connection = yes; Database = school; connection timeout = 30");
        }

//create command

SqlCommand scom = new SqlCommand("insert into students (id,name,address) values(@id,@name,@address)", scon);

//pass parameters

scom.Parameters.Add("id", SqlDbType.Int);
scom.Parameters["id"].Value = textBox1.Text;

           scom.Parameters.Add("name", SqlDbType.VarChar);
            scom.Parameters["name"].Value = this.textBox2.Text;

            scom.Parameters.Add("address", SqlDbType.VarChar);
            scom.Parameters["address"].Value = this.textBox6.Text;


            scon.Open();
            scom.ExecuteNonQuery();
            scon.Close();
            reset();

        }

also check solution here: http://solutions.musanitech.com/?p=6


Change this line:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";

to this:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

Your insert command is expecting text, and you need single quotes (') between the actual value so SQL can understand it as text.

EDIT: For those of you who aren't happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.


You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.


Code To insert Data in Access Db using c#

Code:-

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

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

You probably need quotes around those string fields, but, you should be using parameterized queries!

cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;

Incidentally, your original query could have been fixed like this (note the single quotes):

"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

but this would have made it vulnerable to SQL Injection attacks since a user could type in

'; drop table users; -- 

into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str