【发布时间】:2018-06-21 13:08:43
【问题描述】:
我是 C# 的新手,我有一个数据库,我需要用 windows 窗体填充,将数据插入表的按钮具有以下代码:
private void btnAddEmployee_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("server=.\\server1; database = PMS; Integrated security=true;");
SqlDataAdapter da = new SqlDataAdapter("INSERT INTO tblEmployees cid, empID, empFirstName, empMidName, "
+"empLastName, empAge, empTitle, empAddress, empRank, empSalary, empEmail, empPhone, "
+"empMobile, Notes, userName, usrPassword, usrAccessLevel, empActive, empMarked, empType "
+"VALUES ('" + this.txtID + "', '" + this.txtEmpID + "', '" + this.txtFirstName + "','" + this.txtMidName + "'," +
" '" + this.txtLastName + "', '" + this.txtEmpAge + "', '" + this.txtJobTitle + "', '" + this.txtAddress + "', " +
" '" + this.cmbRank + "', '" + this.txtSalary + "', '" + this.txtEmail + "', '" + this.txtPhone + "', " +
" '" + this.txtMobile + "', '" + this.txtNote + "', '" + this.txtUserName + "', '" + this.txtPassword + "', " +
" '" + this.cmbAcsLevel + "', '" + this.txtActive + "', '" + this.txtMarked + "', '" + this.txtType + "')", cn);
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
object o = da.SelectCommand.ExecuteNonQuery();
cn.Close();
}
但是点击按钮后我得到以下错误:
System.Data.SqlClient.SqlException: 'cid' 附近的语法不正确。'
【问题讨论】:
-
字段名称周围缺少括号。应该是
INSERT INTO tblEmployees (cid,..... empType ) -
另外,阅读 SQL 注入以及如何使用参数化查询来防止它。您的代码非常不安全。
-
即使使用表单应用程序,您也应该练习安全并使用 parameters 将 SQL code 和 data 分开,而不是通过字符串操作将它们组合在一起
-
另外考虑不要将数字数据存储为字符串(例如薪水)。还可以考虑存储出生日期,而不是年龄(因为年龄不断变化)。
标签: c# sql visual-studio