首页 > 解决方案 > c# windows窗体(添加信息访问数据库)

问题描述

我正在尝试向数据库添加信息,但总是出错这是我现在的代码

 public partial class User : Form
{

    public OleDbConnection conect = new OleDbConnection();
    public User()
    {
        InitializeComponent();
        conect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mhamad\Desktop\form\Item.mdb;
                                        Persist Security Info=False;";
    }


    private void User_Load(object sender, EventArgs e)
    {
        try
        {
            conect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = conect;
            command.CommandText = "select * from Item ";

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                combo.Items.Add(reader["Item_Name"].ToString());

            }
            conect.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
    }

    private void combo_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            conect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = conect;
            command.CommandText = "select * from Item where Item_Name='"+combo.Text+"'";

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                item_id.Text = reader["Item_ID"].ToString();

                Price.Text = reader["Item_Price"].ToString();
            }
            conect.Close();

        }
        catch(Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
    }

    private void Buy_Click(object sender, EventArgs e)
    {
        try
        {
            conect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = conect;
            command.CommandText = "insert into Admin_Items ([Item_Name],[Price]) value('" + combo.Text + "','" + Price.Text + "')";

            MessageBox.Show("Success");
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" +ex);
        }

所以这是我现在的代码当我尝试将信息添加到数据库时总是给我这个错误错误代码 这是我的数据库数据库图片 我使用该代码为我的注册表单插入数据并且它与出问题我想将组合框中显示的项目和价格添加到数据库之后,我想将该数据库链接到要显示的管理表单,但我现在被困在这里
这是错误代码系统。 Data.OleDb.OleDbException:'找不到输出表'Admin_Items'。' 来自代码 command.ExecuteNonQuery();

标签: c#winformsms-access

解决方案


您应该编辑插入查询

   cmd.CommandType = CommandType.Text; 
   cmd.CommandText = "insert into Admin_Items (Item_Name ,Price) values (@item, @price)";
   cmd.Parameters.AddWithValue("@item", combo.Text);
   cmd.Parameters.AddWithValue("@price", Price.Text); 

希望会奏效

看看这个


推荐阅读