C#INSERT TO访问数据库创建2个数据库条目而不是1

时间:2014-10-17 13:04:21

标签: c# mysql visual-studio-2010 ms-access

我创建了一个C#程序,用于将数据插入到Access数据库中,并带有一些众所周知的代码。

每次运行代码时,我都会在数据库中获得两个条目

namespace Quotes
{
public partial class QuotesForm : Form
{
    private OleDbConnection quotescon;
    private OleDbCommand oledbcmd = new OleDbCommand();
    private string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\Quotes.mdb;Persist Security Info=False";

    public QuotesForm()
    {
        quotescon = new OleDbConnection(connect);
        InitializeComponent();
    }

    private void btn_insert_Click(object sender, EventArgs e)
    {
        int quote = Convert.ToInt32(txtb_Quotenumber.Text);
        quotescon.Open();
        oledbcmd.Connection = quotescon;
        oledbcmd.CommandText = "insert into table1 ([Quote number], Account, Made, Approved) values ('" + quote + "','" + this.txtb_name.Text + "','" + this.date_created.Text + "','" + this.comboBox1.Text +"');";
        oledbcmd.ExecuteNonQuery();
        int temp = oledbcmd.ExecuteNonQuery();
        if(temp > 0)
        {
            txtb_Quotenumber.Text = null;
            txtb_name.Text = null;
            MessageBox.Show("Entry has been Successfuly Added to Database","Data Added",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Data entry has not been added Successfuly, Please try again", "Failed To add Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        quotescon.Close();

    }

2 个答案:

答案 0 :(得分:5)

因为您执行了两次命令。

一个

oledbcmd.ExecuteNonQuery();

另一个

int temp = oledbcmd.ExecuteNonQuery();

只需删除第一个。

来自SqlCommand.ExecuteNonQuery method

  

对连接执行 Transact-SQL语句并返回   受影响的行数。

但更重要的是,您应始终使用parameterized queries。这种字符串连接对SQL Injection攻击是开放的。

并使用using statement处理您的OleDbConnectionOleDbCommand

using(OleDbConnection quotescon = new OleDbConnection(connect))
using(OleDbCommand oledbcmd= con.CreateCommand())
{
    oledbcmd.CommandText = @"insert into table1 ([Quote number], Account, Made, Approved)
                            values(?, ?, ?, ?)";
    oledbcmd.Parameters.AddWithValue("@number", quote);
    oledbcmd.Parameters.AddWithValue("@account", this.txtb_name.Text);
    oledbcmd.Parameters.AddWithValue("@made", this.date_created.Text);
    oledbcmd.Parameters.AddWithValue("@approved", this.comboBox1.Text);
    int temp = oledbcmd.ExecuteNonQuery();

    if(temp > 0)
    {
        txtb_Quotenumber.Text = null;
        txtb_name.Text = null;
        MessageBox.Show("Entry has been Successfuly Added to Database","Data Added",MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
    else
    {
        MessageBox.Show("Data entry has not been added Successfuly, Please try again", "Failed To add Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

答案 1 :(得分:2)

您正在使用

执行两次查询
oledbcmd.ExecuteNonQuery();
int temp = oledbcmd.ExecuteNonQuery();