如何在MS Access表中插入Label值

本文关键字:插入 Label Access MS | 更新日期: 2023-09-27 18:11:52

嗨,我想在ms access中基本插入标签中的值到表中。我已经做了它的文本框,它存储,但对于标签,当我试图存储它没有错误显示,但它不存储在数据库中,我该怎么办?我使用以下代码

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();
        }
    }

如何在MS Access表中插入Label值

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());
    }
}