Reputation: 5
I've made sure everything pertains to the column types in the database, but I keep getting an SQLCeException. Can anyone tell me what's wrong with this code?
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();
}
Upvotes: 0
Views: 330
Reputation: 20572
Use Parameters to prevent SQL injection, and the Columns names, because you are relying in the quantity, and order of your table's columns and it will likely change in the future (I'm guessing the column names):
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
By the way try to not use spaces in table and columns names ;-)
Upvotes: 3
Reputation: 6729
As Lorenzo said, the string values must be enclosed with single quotes, but please read this page which explains why you shouldn't build a query this way, and shows you how to do it with parameters.
Upvotes: 0
Reputation: 29427
Your fields of type string/varchar shall be enclosed in single quotes!
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
"'" + first + "',"
and so on...
Also, as somebody else already commented you're going to greatly expose your code to SQL injection attacks
Upvotes: 2