我正在尝试将数据添加到Access数据库中,到目前为止,这就是我所拥有的。
try
{
connection.Open();
String dataInsert = "INSERT into ClientsT (FirstName, LastName, Address, Email, Phone, CellPhone, Notes) values('" + boxAddName.Text.ToString() + "', '" + boxAddLastName.Text + "', '" + boxAddAdress.Text + "', '" + boxAddEmail.Text + "', '" + boxAddPhone + "', '" + boxAddCellPhone + "','" + boxAddObs.Text + "')";
OleDbCommand command = new OleDbCommand(dataInsert, connection);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Client added,");
} catch(Exception ex){
MessageBox.Show("Error :" + ex);
}
}
它并没有给我带来任何错误之门,代码执行得很好,但是没有任何内容添加到数据库中。
请注意,我对c#还是陌生的,这是我第一次使用数据库。
现在在那儿等一下!
您正在引入潜在的灾难性安全漏洞。让我告诉你为什么:
String dataInsert = "INSERT into ClientsT (FirstName, LastName, Address, Email, Phone, CellPhone, Notes) values('" + boxAddName.Text.ToString() + "', '" + boxAddLastName.Text + "', '" + boxAddAdress.Text + "', '" + boxAddEmail.Text + "', '" + boxAddPhone + "', '" + boxAddCellPhone + "','" + boxAddObs.Text + "')";
特别是这些行:
boxAddName.Text.ToString() // You're converting a string to a string, which is redundant. :P You are also missing a semicolon here.
boxAddLastName.Text
boxAddAdress.Text
boxAddEmail.Text
boxAddPhone // Not a security problem, but you're inserting the TextBox control, not it's text.
boxAddCellPhone // Same as above.
boxAddObs.Text
您要做的基本上是允许用户将他们想要的任何内容放入数据库中。这样,用户可以插入他们想要的任何内容,甚至使用SQL injection
漏洞利用程序。您应该始终清理输入内容。
您可以执行以下操作:
string Query = "INSERT into ClientsT (FirstName, LastName, Address, Email, Phone, CellPhone, Notes) values(@FirstName, @LastName, @Address, @Email, @Phone, @CellPhone, @Notes)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(Query))
{
connection.Open();
// Please make sure you edit the SqlDbType to the correct SQL Data Type. They are VarChar by default in this example. It's on you to fix that.
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar) = boxAddName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar) = boxAddLastName.Text;
cmd.Parameters.Add("@Address", SqlDbType.VarChar) = boxAddAddress.Text;
cmd.Parameters.Add("@Email", SqlDbType.VarChar) = boxAddEmail.Text;
cmd.Parameters.Add("@Phone", SqlDbType.VarChar) = boxAddPhone.Text;
cmd.Parameters.Add("@CellPhone", SqlDbType.VarChar) boxAddCellPhone.Text;
cmd.Parameters.Add("@Notes", SqlDbType.VarChar) = boxAddNotes.Text;
// Insert writing code here.
}
您的问题很简单:
您正在尝试多次插入TextBox
控件。看看boxAddPhone
,和boxAddCellphone
:你需要使用TextBoxName.Text
,不TextBoxName
。因此,它将引发异常,并且由于您正在捕获所有异常,因此您将不知道出了什么问题。可能是任何东西。
最后,您还要添加boxAddObs
,它不会与第一条INSERT INTO ClientsT (...)
语句一起插入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句