0

嗨,我想基本上将标签中的值插入到 ms 访问中的表中。我已经为文本框完成了它并且它存储但用于标签当我尝试存储它时没有显示错误但它没有存储在数据库中我该怎么办?我正在使用以下代码

static OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
    OleDbDataAdapter ada = new OleDbDataAdapter();
    OleDbCommand cmd = new OleDbCommand();
    OleDbDataReader dr;


protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string str = "insert into Orders (Products, Amount)" + " values (@p1, @p2)";
            con.Open();
            cmd = new OleDbCommand(str, con);
            cmd.Parameters.AddWithValue("@p1", Label18.Text);
            cmd.Parameters.AddWithValue("@p2", Label16.Text);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch
        {
            Console.WriteLine("Exception Occured");
        }
        finally
        {
            if (con != null && con.State != ConnectionState.Closed)
            { con.Close(); }
        }
    }

我也尝试将文本框值存储到“地址”列下的同一个表“订单”中,但面临同样的上述问题......该表没有更新。我之前已经将此代码用于不同表格的其他文本框等,并且效果很好。

static OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
    OleDbDataAdapter ada = new OleDbDataAdapter();
    OleDbCommand cmd = new OleDbCommand();
    OleDbDataReader dr;

 protected void Button1_Click(object sender, EventArgs e)
    {

        {
            string str = "insert into Orders (Address)" + " values (@p1)";
            con.Open();
            cmd = new OleDbCommand(str, con);
            cmd.Parameters.AddWithValue("@p1", TextBox1.Text);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
4

1 回答 1

0

OLE DB .NET 提供程序不支持将参数传递给 SQL 语句的命名参数

尝试

   string str = "insert into Orders (Products, Amount) values (?,?)";

您可以更改代码如下

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb"))
        using (OleDbCommand cmd = new OleDbCommand("insert into Orders (Products, Amount) values (?,?)", con))
        {
            cmd.Parameters.AddWithValue("@p1", Label18.Text);
            cmd.Parameters.AddWithValue("@p2", int.Parse(Label16.Text));
            con.Open();
            int no = cmd.ExecuteNonQuery();

            Console.WriteLine("number of rows affected = " + no);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception Occured :" ex.ToString());
    }
}
于 2013-05-02T09:35:12.033 回答