列名sql错误无效

我试图将数据输入我的数据库,但它给了我以下错误:

列名无效

这是我的代码

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

始终尝试使用参数化的SQL查询以防止恶意发生,因此您可以重新排列代码,如下所示:

还要确保您的表的列名与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(); } 

您可能需要围绕这些字符串字段的引号,但是, 您应该使用参数化查询!

 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; 

顺便说一句,您的原始查询可能已经这样修复(请注意单引号):

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

由于用户可以输入, 这会使其易受SQL注入攻击

 '; drop table users; -- 

进入你的一个文本框。 或者更糟糕的是,可怜的Daniel O’Reilly每次都会打破你的疑问。

改变这一行:

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

对此:

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

您的insert命令需要文本,并且您需要在实际值之间使用单引号(’),以便SQL可以将其理解为文本。

编辑 :对于那些对这个答案不满意的人,我想指出这个代码在SQL注入方面存在问题。 当我回答这个问题时,我只考虑了一个问题,那就是他的代码中缺少单引号,我指出了如何修复它。 亚当已经发布了一个更好的答案(我投了赞成票),在那里他解释了注射问题,并展示了一种预防方法。 现在放松,快乐的家伙。

你的问题是你的字符串是不加引号的。 这意味着它们被数据库引擎解释为列名。

您需要创建参数才能将值传递给查询。

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

您永远不应该编写将SQL和参数连接成字符串的代码 – 这会将您的代码打开到SQL注入 ,这是一个非常严重的安全问题。

使用绑定参数 – 在这里看到一个很好的方法…

代码使用c#在Access Db中插入数据

码:-

 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 { ///  /// Interaction logic for MainWindow.xaml ///  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 = ""; } } } 

你必须使用'"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

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

注意额外的单引号。

首先创建数据库名称“School”而不是创建表“学生”,其中包含以下列1. id 2. name 3. address

现在打开visual studio并创建连接:

 命名学校
 {
    公共部分类Form1:表格
     {
         SqlConnection scon;


        公共Form1()
         {

            的InitializeComponent();

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

 //创建命令

 SqlCommand scom = new SqlCommand(“插入学生(id,name,address)值(@ id,@ name,@ address)”,scon);

 //传递参数

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

         } 

还可以在这里查看解决方案: http : //solutions.musanitech.com/?p = 6

您的问题似乎是Name关键字。 而是使用FullName或firstName和lastName,总是尝试并记住也使用CamelCase。

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