每次我点击插入这个代码都会很好地插入,但是当我打开访问数据库时,这就是它如何放在每个单元格System.Windows.Forms.TextBox,Text: 这是我的插入代码。
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
conn.Open();
String my_querry = (@"INSERT INTO System (Name, Address, Conperson, Scope_of_certification, Certification, Date_issued,
Dateofsurv, Dateofrecerti, Remark, certi_fee)
VALUES ('" + txtName + "','" + txtAddress + "','" + txtConperson + "','" + txtscoperofcerti + "','" + txtcertification + "','" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "','" + dateTimePicker2.Value.ToString("MM/dd/yyyy") + "','" + dateTimePicker3.Value.ToString("MM/dd/yyyy") + "','" + txtRemark + "','" + txtcertfee + "')");
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
答案 0 :(得分:3)
您正在直接访问TextBox
控件,您需要访问其Text
属性才能访问其内容。
替换它:
txtName
有了这个:
txtName.Text
其他控件相同。
建议:您的查询对SQL注入攻击是开放的,使用参数化查询来避免它们。
答案 1 :(得分:0)
请停止使用连接的查询字符串,因为这会让您对SQL注入攻击开放并导致其他多个问题,例如传递DateTime
值时!使用像这样的参数化查询。另请注意,您需要将TextBox.Text
而非TextBox
插入数据库以获取正确的值:
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
conn.Open();
String my_querry = @"INSERT INTO System (Name, Address, Conperson, Scope_of_certification, Certification, Date_issued,
Dateofsurv, Dateofrecerti, Remark, certi_fee)
VALUES (@name, @address, @conPerson, @scope, @cert, @dateIssued, ...");
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
...
cmd.Parameters.AddWithValue("@dateIssued", dateTimePicker1.Value);
...
cmd.ExecuteNonQuery();
conn.Close();
}
另外:请习惯将日期存储为DateTime
或Date
,而不是文本。另请注意我如何使用DateTime.Now
作为参数值。它适用于所有数据类型。在您的情况下(直到您更改为DateTime/Date
列类型),您需要使用dateTimePicker1.Value.ToString("MM/dd/yyyy")
。