【发布时间】:2021-02-07 01:39:36
【问题描述】:
我对 C# 和 SQL Server 完全陌生。我正在构建一个简单的程序,其中包含患者,用户输入后应在屏幕上显示他们的数据,但每当我尝试将数据添加到数据库时,都会出现此错误:
System.Data.SqlClient.SqlException: '无效的列名
这是我的代码
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 WindowsFormsApp1
{
public partial class Patients: Form
{
SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\SAMSUNG\Documents\MHSdb.mdf;Integrated Security=True;Connect Timeout=30");
public Patients()
{
InitializeComponent();
}
void populate()
{
Con.Open();
string query = " select * from PatientsTable";
SqlDataAdapter da = new SqlDataAdapter(query, Con);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var view = new DataSet();
da.Fill(view);
PatGV.DataSource = view.Tables[0];
Con.Close();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
this.Hide();
Home h = new Home();
h.Show();
}
private void textBox12_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Con.Open();
string query = "insert into PatientsTable values(" + PatID.Text + ", " + PatName.Text + "," + FileNumber.Text + "," + CitizenID.Text + "," + Gender.Text + ", " + Birthdate.Text + ", " + Nationality.Text + ", " + PhoneNum.Text + ", " + Email.Text + "," + Country.Text + "," + City.Text + "," + Street.Text + "," + Address1.Text + "," + Address2.Text + "," + ContactPerson.Text + "," + ContactRelation.Text + "," + ContactPhone.Text + ", " + FirstVIstit.Text + "," + c.Text + ")";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Patient Added Sucecsfully");
Con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Home h = new Home();
h.Show();
this.Hide();
}
private void PatGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
populate();
}
private void button2_Click(object sender, EventArgs e)
{
if (PatID.Text == "")
MessageBox.Show("Enter the Patient ID");
else
{
Con.Open();
string query = "delete from PatientsTable where PatID" + PatID.Text + "";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Patient deleted Successfully!");
Con.Close();
populate();
}
}
private void PatID_TextChanged(object sender, EventArgs e)
{
}
}
}
这是我的数据库代码
CREATE TABLE [dbo].[PatientsTable] (
[PatId] INT NOT NULL,
[PatientName] CHAR (10) NOT NULL,
[FileNumber] INT NOT NULL,
[CitizenID] CHAR (10) NOT NULL,
[Birthdate] DATE NULL,
[Nationality] CHAR (10) NOT NULL,
[PhoneNum] INT NOT NULL,
[Email] CHAR (10) NULL,
[Country] CHAR (10) NOT NULL,
[City] CHAR (10) NOT NULL,
[Street] CHAR (10) NOT NULL,
[Address1] CHAR (10) NOT NULL,
[Address2] CHAR (10) NOT NULL,
[ContactPerson] CHAR (10) NOT NULL,
[ContactRelation] CHAR (10) NOT NULL,
[ContactPhone] INT NOT NULL,
[FirstVIstit] DATE NULL,
[RecordCreationDate] DATE NULL,
[Gender] CHAR (10) NULL,
PRIMARY KEY CLUSTERED ([PatientsTable] ASC)
);
这是错误日志
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Invalid column name 'yaman'.
Invalid column name 'Male'.
Invalid column name 'sytian'.
Invalid column name 'yam'.
Invalid column name 'uwei'.
Invalid column name 'gt'.
Invalid column name 'uywyr'.
Invalid column name 'ywry'.
Invalid column name 'fbk'.
Invalid column name 'lina'.
Invalid column name 'fanily'.
Source=.Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at WindowsFormsApp1.Patients.button4_Click(Object sender, EventArgs e) in C:\Users\SAMSUNG\source\repos\WindowsFormsApp1\WindowsFormsApp1\Patients.cs:line 49
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApp1.Program.Main() in C:\Users\SAMSUNG\source\repos\WindowsFormsApp1\WindowsFormsApp1\Program.cs:line 19
我查看了其他问题,但似乎没有一个问题像我的问题
【问题讨论】:
-
您在这里有 3 个查询,并且您方便地省略了导致问题的查询。但是,您的删除查询是 munted,并且容易受到 sql 注入攻击。插入查询也可能失败。考虑使用参数化查询并仔细检查 sql
-
@00110001 的意思是说它应该是
delete from PatTbl where PatID=,你应该真正使用SQL参数来避免注入。其他问题:你需要用using处理连接、命令、适配器等对象,不要缓存连接对象。此外,指定要插入的列,例如insert into table (col1,col2) values (...以及 AttachDbFileName is going to cause issues。另外,不要在连接打开时使用MessageBox阻止或进行繁重的处理 -
SQL Injection alert - 你应该永远将你的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL注入 - 签出Little Bobby Tables
-
谢谢大家的cmets,我已经修改了代码,你能重新检查一下吗?
-
您的插入语句错误,应该是这样的 INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
标签: c# .net sql-server