简体   繁体   English

无效的列名 sql 错误

[英]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();
}

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但这会使它容易受到 SQL 注入攻击,因为用户可以输入

'; drop table users; -- 

into one of your textboxes.进入您的文本框之一。 Or, more mundanely, poor Daniel O'Reilly would break your query every time.或者,更平凡的是,可怜的 Daniel O'Reilly 每次都会打断您的查询。

Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:始终尝试使用参数化 sql 查询来防止恶意发生,因此您可以重新排列代码如下:

Also make sure that your table has column name matches to Name , PhoneNo , Address .还要确保您的表的列名与NamePhoneNoAddress相匹配。

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}

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.您的插入命令需要文本,您需要在实际值之间使用单引号 ('),以便 SQL 可以将其理解为文本。

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.编辑:对于那些对这个答案不满意的人,我想指出此代码在 SQL 注入方面存在问题。 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. Adam 发布了一个更好的答案(我投了赞成票),他解释了注射的问题并展示了一种预防方法。 Now relax and be happy guys.现在放松一下,做个快乐的人。

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);

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.您永远不应该编写将 SQL 和参数连接为字符串的代码 - 这会导致您的代码受到SQL 注入,这是一个非常严重的安全问题。

Use bind params - for a nice howto see here ...使用绑定参数 - 在这里看到一个很好的方法......

Code To insert Data in Access Db using c#使用c#在Access Db中插入数据的代码

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();
    }
}
}
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 = "";
        }
    }
}

You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'你必须使用'"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"而不是"+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.注意额外的单引号。

Your issue seems to be the Name keyword.您的问题似乎是 Name 关键字。 Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.而是使用 FullName 或 firstName 和 lastName,始终尝试并记住也使用 CamelCase。

first create database name "School" than create table "students" with following columns 1. id 2. name 3. address首先创建数据库名称“School”,然后创建表“students”,其中包含以下列 1. id 2. name 3. address

now open visual studio and create connection:现在打开visual studio并创建连接:

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也在这里检查解决方案: http : //solutions.musanitech.com/?p=6

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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