简体   繁体   中英

insert into database

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();
}

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 ;-)

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

正如Lorenzo所说,字符串值必须用单引号引起来,但是请阅读此页 ,它解释了为什么您不应该以这种方式构建查询,并向您展示了如何使用参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM