【发布时间】:2014-12-14 19:55:43
【问题描述】:
我正在使用 Visual Studio 2012 并创建了一个简单的应用程序。我创建了一个名为 Personnel 的数据库,其中包含一个名为 Employee 的表。我已经解决了所有语法错误并且代码看起来不错,但是当我尝试使用表单将数据插入数据库时,我的表单 - Form1.cs 会引发错误。
在我将数据插入字段 - ID、姓名、职位和每小时工资率后,然后单击添加,它在职位字段上阻塞,并且错误读取我在该字段中键入的任何内容。
例如,如果我在该表单字段中输入“经理”,错误窗口会显示:
“经理”附近的语法不正确。
这里的任何帮助将不胜感激。这是我的代码:
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 Personnel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'personnelDataSet.Employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::Personnel.Properties.Settings.Default.PersonnelConnectionString);
try
{
string sql = "INSERT INTO Employee (employeeID,Name,Position,HourlyPayRate) values("+txtemployeeID.Text+",'"+txtName.Text+",'"+txtPosition.Text+",'"+txtHourlyPayRate.Text+"')";
SqlCommand exeSQL = new SqlCommand(sql, cn);
cn.Open();
exeSQL.ExecuteNonQuery();
MessageBox.Show("New record added!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
private void btnRef_Click(object sender, EventArgs e)
{
this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);
}
}
}
【问题讨论】:
-
您的 sql 语法在其中一个字段值之后缺少单引号;名称
-
SQL Injection alert - 你应该不将你的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入
-
加上@marc 所说的!
-
感谢所有发布的内容。由于您的许多建议,我现在工作得很好。谢谢!
标签: c# sql sql-server winforms