【发布时间】:2018-11-06 16:09:49
【问题描述】:
我正在尝试从 Visual Studio 插入数据库表,但我遇到了同样的错误,我不知道会是什么。
System.Data.SqlClient.SqlException: '无效的列名'
这是我的代码,我做了 2 个类,Gateway、Dept 和 Form1:
namespace insertar
{
class Dept
{
public string Dept_No { get; set; }
public string DNombre { get; set; }
public string Loc { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace insertar
{
class Gateway
{
public bool Save(Dept dept)
{
Form1 form = new Form1();
string connectionString = @"Data Source=DESKTOP-IE39262;Initial Catalog=Hospital;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
//connection.Open();
/*string query = @"INSERT INTO Dept VALUES (" + dept.Dept_No + "," + dept.DNombre +
"," + dept.Loc + ")";*/
SqlCommand command = new SqlCommand("INSERT INTO Dept(Dept_No, DNombre, Loc)" + "VALUES (" + dept.Dept_No + "," + dept.DNombre +
"," + dept.Loc + ")", connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
return true;
}
}
}
private void guardarbtn_Click(object sender, EventArgs e)
{
Dept dept = new Dept();
dept.Dept_No = dept_no.Text;
dept.DNombre = dnombre.Text;
dept.Loc = loc.Text;
Gateway gateaway = new Gateway(); //class gateway
gateaway.Save(dept);
MessageBox.Show("Departamento insertado exitosamente");
dept_no.Text = "";
dnombre.Text = "";
loc.Text = "";
}
【问题讨论】:
-
你为什么不参数化你的 SQL? SQL 注入远非你的朋友。
-
您是否真的检查过数据库以确保列存在?
-
您的字符串不带引号传递,导致服务器将它们解释为列名。阅读如何使用
SqlParameter。
标签: c# sql-server visual-studio