【问题标题】:Data not stored in Access db with C# ad.InsertCommand未使用 C# ad.InsertCommand 存储在 Access db 中的数据
【发布时间】:2014-02-03 11:14:36
【问题描述】:

我在 C# 中有以下代码,用于与 DB 的接口。我在界面上的 TextBoxes 中引入值。没有错误,但是执行时,数据不会存储在使用 Microsoft Access 2010 创建的数据库中。我将在此处给出完整的代码。感谢您的回答!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {   
        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\lumi\\Desktop\\Test_DataB.accdb");
 OleDbDataAdapter ad = new OleDbDataAdapter();
DataSet ds = new DataSet();


        public Form1()
        {
            InitializeComponent();
        }

        private void indexBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.indexBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.test_DataBDataSet);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'test_DataBDataSet.Index' table. You can move, or remove it, as needed.
            this.indexTableAdapter.Fill(this.test_DataBDataSet.Index);

        }

        private void button1_Click(object sender, EventArgs e)
        {
               try
    {       con.Open();               
            ad.InsertCommand = new OleDbCommand("Insert @Birth_month, @Firstname, @Surname, @ID", con);
            ad.InsertCommand.Parameters.Add("@Birth_month", OleDbType.Numeric).Value = int.Parse(textBox1.Text);
            ad.InsertCommand.Parameters.Add("@Firstname", OleDbType.VarChar).Value = textBox2.Text.ToString();
            ad.InsertCommand.Parameters.Add("@Surname", OleDbType.VarChar).Value = textBox3.Text.ToString();
            ad.InsertCommand.Parameters.Add("@ID", OleDbType.Numeric).Value = int.Parse(textBox4.Text);
            ad.InsertCommand.ExecuteNonQuery();
            con.Close();
    }


               catch (Exception ex)
               {
                   MessageBox.Show(ex.Message);
               }


        }
    }
}

【问题讨论】:

  • 什么..?您的 OleDbCommand 看起来不是有效的 sql 语句。 o.O
  • 我翻译了,对不起!

标签: c# database-connection ms-access-2010 sql-insert oledbcommand


【解决方案1】:

INSERT 命令的正确语法是

INSERT INTO tablename VALUES(list of comma separated values or parameters)

所以你查询缺少一些非常重要的东西,即插入应该发生的表名。
我有点困惑,您没有从中收到任何错误消息。

ad.InsertCommand = new OleDbCommand(@"Insert INTO table 
                                      VALUES (@Birth_month, @Firstname, @Surname, @ID)", con);

为了这个查询的目的,您可以将 OleDbDataAdapter 排除在外。不需要

OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue(.....);
....
cmd.ExecuteNonQuery(); 

请记住,这种形式的 INSERT 要求您按照定义的确切顺序为基础表中的字段指定每个值作为参数。如果你的参数比列少,那么你需要在 VALUES 之前指定一个列列表

INSERT INTO tablename (comma separated list of columns) VALUES (comma separated list of values)

顺便说一下,这是首选的方法。特别是,这使您免受架构更改的影响,例如添加一个新的可空列会破坏第一个语句(没有列列表的语句)

【讨论】:

    【解决方案2】:

    您不能参数化列名。您可以参数化您的

    这里是INSERT (Transact-SQL)的语法

    INSERT 
    {
            [ TOP ( expression ) [ PERCENT ] ] 
            [ INTO ] 
            { <object> | rowset_function_limited 
              [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
            }
        {
            [ ( column_list ) ] 
            [ <OUTPUT Clause> ]
            { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
            | derived_table 
            | execute_statement
            | <dml_table_source>
            | DEFAULT VALUES 
            }
        }
    }
    

    根据你的情况;

    INSERT INTO YourTableName VALUES(@Birth_month, @Firstname, @Surname, @ID)
    

    如果需要,您应该添加列名。

    【讨论】:

      【解决方案3】:

      问题:您的INSERT INTO 声明无效。

      INSERT INTO 语句的语法:

      INSERT INTO [TableName]([col1],[col2],[coln]) values(@val1,@val2,@valn);

      解决方案:假设你的表名是UserInfo

      con.Open();               
      ad.InsertCommand = new OleDbCommand("INSERT INTO UserInfo values(@Birth_month, @Firstname, @Surname, @ID", con);   
      ad.InsertCommand.Parameters.Add("@Birth_month", OleDbType.Numeric).Value = int.Parse(textBox1.Text);
      ad.InsertCommand.Parameters.Add("@Firstname", OleDbType.VarChar).Value = textBox2.Text.ToString();
      ad.InsertCommand.Parameters.Add("@Surname", OleDbType.VarChar).Value = textBox3.Text.ToString();
      ad.InsertCommand.Parameters.Add("@ID", OleDbType.Numeric).Value = int.Parse(textBox4.Text);
      ad.InsertCommand.ExecuteNonQuery();
      con.Close();
      

      【讨论】:

        【解决方案4】:

        您的插入查询似乎有误

         ad.InsertCommand = new OleDbCommand  Insert into tablename (Birth_month,Firstname,Surname,id) values (@Birth_month, @Firstname, @Surname, @ID)
         ad.InsertCommand.Parameters.Add("@Birth_month", OleDbType.Numeric).Value = int.Parse(textBox1.Text);
         ad.InsertCommand.Parameters.Add("@Firstname", OleDbType.VarChar).Value = textBox2.Text.ToString();
         ad.InsertCommand.Parameters.Add("@Surname", OleDbType.VarChar).Value = textBox3.Text.ToString();
         ad.InsertCommand.Parameters.Add("@ID", OleDbType.Numeric).Value = int.Parse(textBox4.Text);
         ad.InsertCommand.ExecuteNonQuery();
         con.Close();
        

        确保您的连接字符串类似于
        Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;

        【讨论】:

          【解决方案5】:

          试试这个代码

            using System;
              using System.Collections.Generic;
              using System.ComponentModel;
              using System.Data;
              using System.Drawing;
              using System.Linq;
              using System.Text;
              using System.Windows.Forms;
              using System.Data.OleDb;
          
              namespace WindowsFormsApplication5
              {
                  public partial class Form1 : Form
                  {
                      OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\lumi\\Desktop\\Test_DataB.accdb");
                      OleDbDataAdapter ad = new OleDbDataAdapter();
                      DataSet ds = new DataSet();
          
          
                      public Form1()
                      {
                          InitializeComponent();
                      }
          
                      private void indexBindingNavigatorSaveItem_Click(object sender, EventArgs e)
                      {
                          this.Validate();
                          this.indexBindingSource.EndEdit();
                          this.tableAdapterManager.UpdateAll(this.test_DataBDataSet);
          
                      }
          
                      private void Form1_Load(object sender, EventArgs e)
                      {
                          // TODO: This line of code loads data into the 'test_DataBDataSet.Index' table. You can move, or remove it, as needed.
                          this.indexTableAdapter.Fill(this.test_DataBDataSet.Index);
          
                      }
          
                      private void button1_Click(object sender, EventArgs e)
                      {
                          try
                          {
          
                         con.Open();  
          
                              SqlCeCommand insert_command = new SqlCeCommand("Luna_nasterii,Nume,Prenume,Nr_fisa) " + "VALUES (@Luna_nasterii, @Nume, @Prenume, @Nr_fisa)", con);
          
                              insert_command.Parameters.AddWithValue("@Luna_nasterii", OleDbType.Numeric).Value = int.Parse(textBox1.Text);
                              insert_command.Parameters.AddWithValue("@Nume",OleDbType.VarChar).Value = textBox2.Text.ToString();
                              insert_command.Parameters.AddWithValue("@Prenume",  OleDbType.VarChar).Value = textBox3.Text.ToString();
                              insert_command.Parameters.AddWithValue("@Nr_fisa",  OleDbType.Numeric).Value = int.Parse(textBox4.Text);
          
          
                              create_adapt.InsertCommand = insert_command;
                              insert_command.ExecuteNonQuery();
                              con.close();
                          }
          
          
                          catch (Exception ex)
                          {
                              MessageBox.Show(ex.Message);
                          }
          
          
                      }
                  }
              }
          

          【讨论】:

          • 错误:找不到类型或命名空间名称“SqlCeCommand”
          【解决方案6】:

          确实,我的第一个错误是我没有注意的 INSERT 语句的语法。但即使更正,它也不起作用。没有数据存储在数据库中。问题是 Access 数据库未本地化到项目的 BIN 文件夹中。当我移动它时,一切正常。谢谢大家的帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-06-10
            • 2011-02-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-10
            相关资源
            最近更新 更多