我已经确定所有内容都与数据库中的列类型有关,但我不断收到SQLCeException。谁能告诉我这段代码有什么问题?
private void ANDPaddDriverButton_Click(object sender, EventArgs e)
{
string first = ANDPfirstNametextBox.Text;
string last = ANDPlastNametextBox.Text;
string mid = textBox5.Text;
string phone = ANDPphonetextBox.Text;
string social = ANDPsSNtextBox.Text;
// EmployeeType="Employee"
string city = ANDPCityTextbox.Text;
string state = ANDPStatetextBox.Text;
string zip = ANDPzipCodetextbox.Text;
string email = ANDPemailtextBox.Text;
string address = ANDPaddressTextBox.Text;
string user = userName.Text;
DBConn.Open();
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
first + "," + last + "," + mid + "," + address + "," + phone + "," + social + ","
+ "Employee" + "," + city + "," + state + "," + zip + "," + email + "," + userName + ")", DBConn);
cmd.ExecuteNonQuery();
DBConn.Close();
}
答案 0 :(得分:3)
使用参数来防止SQL注入和列名称,因为您依赖于表的列的数量和顺序,并且它将来可能会更改(我猜列名称):
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] (First, Last, Mid, Address, Phone, Social, Employee, City, State, Zip, Email, UserName) VALUES (@First, @Last, @Mid, @Address, @Phone, @Social, @Employee, @City, @State, @Zip, @Email, @UserName)", DBConn);
cmd.Parameters.AddWithValue("@First", first);
cmd.Parameters.AddWithValue("@Last", last);
cmd.Parameters.AddWithValue("@Mid", mid);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@Phone", phone);
// etc. each column
顺便说一下,尝试不在表名和列名中使用空格; - )
答案 1 :(得分:2)
您的string / varchar类型的字段应用单引号括起来!
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
"'" + first + "',"
依旧......
此外,正如其他人已经评论过你将大大暴露你的代码到SQL注入攻击
答案 2 :(得分:0)
正如Lorenzo所说,字符串值必须用单引号括起来,但请阅读this page,这解释了为什么不应该以这种方式构建查询,并向您展示如何使用参数进行查询。