简体   繁体   中英

why isn't my c# insert query working?

what is the problem in my code?

private void button1_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";

        String kerdes = Convert.ToString(textBox1.Text);
        String valaszok = Convert.ToString(textBox2.Text);

        OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(@kerdes, @valaszok)");
        cmd.Connection = conn;

        conn.Open();

        if (conn.State == ConnectionState.Open)
        {
            cmd.Parameters.Add("@kerdes", OleDbType.VarChar).Value = kerdes;
            cmd.Parameters.Add("@valaszok", OleDbType.VarChar).Value = valaszok;

            try
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data Added");
                conn.Close();
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Source);
                conn.Close();
            }
        }
        else
        {
            MessageBox.Show("Connection Failed");
        }
    }

When I click the button it says:

Microsoft Office Access Database Engine

I made the database with Access. Any ideas?

OleDbCommand does not support named parameters - use ? instead:

OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.

You need to change your parameters to:

cmd.Parameters.AddWithValue("@kerdes", kerdes);
cmd.Parameters.AddWithValue("@valaszok", valaszok); 

This needs to be done in addition to the above comment of changing your query to:

OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

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