C# 无效的列名sql错误
我正在尝试将数据输入数据库,但出现以下错误: 无效的列名 这是我的密码C# 无效的列名sql错误,c#,sql-server,database,C#,Sql Server,Database,我正在尝试将数据输入数据库,但出现以下错误: 无效的列名 这是我的密码 string connectionString = "Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=AddressBook;Server=Bilal-PC"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cm
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();
}
您可能需要在这些字符串字段周围加引号,但是,您应该使用参数化查询强>
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;
顺便说一句,您的原始查询可以这样修复(请注意单引号):
但这会使它容易受到SQL注入攻击,因为用户可以键入
'; drop table users; --
进入你的一个文本框。或者,更平常的是,可怜的丹尼尔·奥赖利每次都会打断你的提问。更改这行:
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和参数连接为字符串的代码-这会打开您的代码,这是一个非常严重的安全问题
使用bind params-为了更好地了解…请始终尝试使用参数化sql查询以防止恶意事件的发生,这样您就可以按如下方式重新排列代码: 还要确保表的列名与
名称
、电话号码
、地址
匹配
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();
}
使用c在Access数据库中插入数据的代码# 代码:-
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();
}
}
}
首先创建数据库名称“School” 然后创建具有以下列的表“students” 1.身份证件 2.名称 3.地址 现在打开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(); } 名称空间学校 { 公共部分类Form1:Form { sqlconnectionscon; 公共表格1() { 初始化组件(); scon=新的SqlConnection(“数据源=ABC-PC;可信连接=是;数据库=学校;连接超时=30”); } //创建命令 SqlCommand scom=新的SqlCommand(“插入学生(id、名称、地址)值(@id、@name、@address)”,scon); //传递参数 添加(“id”,SqlDbType.Int); scom.Parameters[“id”].Value=textBox1.Text; 添加(“名称”,SqlDbType.VarChar); scom.Parameters[“name”].Value=this.textBox2.Text; 添加(“地址”,SqlDbType.VarChar); scom.Parameters[“address”].Value=this.textBox6.Text; scon.Open(); scom.ExecuteNonQuery(); scon.Close(); 重置(); }
同时检查此处的解决方案:您的问题似乎是Name关键字。不要使用FullName或firstName和lastName,始终尝试并记住也使用CamelCase。
使用System;
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 = "";
}
}
}
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.Data.SqlClient;
使用系统数据;
命名空间WpfApplication1
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
}
私有无效btnAdd_单击(对象发送者,路由目标e)
{
SqlConnection conn=newsqlconnection(@“数据源=WKS09\SQLEXPRESS;初始目录=StudentManagementSystem;集成安全性=True”);
SqlCommand insert=new SqlCommand(“插入dbo.StudentRegistration(ID、名称、年龄、出生日期、电子邮件、注释)值(@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不能为空”);
返回;
}
else if(textBox2.Text==string.Empty)
{
MessageBox.Show(“名称不能为空”);
返回;
}
尝试
{
conn.Open();
insert.ExecuteNonQuery();
MessageBox.Show(“注册完成!”);
}
捕获(例外情况除外)
{
MessageBox.Show(“错误”+ex.Message);
康涅狄格州关闭();
}
}
私有void btnRetrieve\u单击(对象发送方,路由目标)
{
布尔温度=假;
SqlConnection con=newsqlconnection(“server=WKS09\\SQLEXPRESS;database=StudentManagementSystem;Trusted_Connection=True”);
con.Open();
SqlCommand cmd=new SqlCommand(“从dbo.StudentRegistration中选择*,其中ID=”+textBox1.Text.Trim()+”,con);
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
textBox2.Text=dr.GetString(1);
textBox3.Text=dr.GetIn
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 = "";
}
}
}
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();