【问题标题】:Inserting into Access DB using C#使用 C# 插入 Access DB
【发布时间】:2014-05-10 07:01:55
【问题描述】:

我在使用 C# 将新条目插入 Access DB 时遇到了一点问题。我认为问题在于我的插入语句,但我包含了大部分程序,以防万一有人看到另一个严重错误。在将值输入第二种形式后,我遇到的错误发生了。我会说,也许我从第二种表格中获取值时做错了,但是查看我输入的消息框以检查,显然正在接收值。在我关闭消息框后立即抛出此错误,显示条件表达式中的数据类型不匹配。

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

namespace AHamblin_Larrys1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void InitializeDataGridView(string nameOfTable, string[] fieldNames)
    {

        //Define database connection string and dataset
        String connectionString =
                  @"Provider=Microsoft.ACE.OLEDB.12.0;Data"
                + @" Source=C:\Users\cryow_000\Desktop\AhamblinLarrys1.accdb";
        String tableName = nameOfTable;
        String selectStatement = String.Format(
                      "select * from [{0}]", tableName);
        DataSet ds = new DataSet();
        OleDbConnection connection =
              new OleDbConnection(connectionString);

        try
        {
            //Open Database Connection
            connection.Open();
            OleDbDataAdapter da =
                   new OleDbDataAdapter(selectStatement, connection);
            OleDbCommandBuilder cmdB =
                   new OleDbCommandBuilder(da);
            da.MissingSchemaAction =
                   MissingSchemaAction.AddWithKey;

            //Fill the DataSet
            da.Fill(ds, tableName);

            // Initialize a DataGridView.
            dataGridView1.Rows.Clear();
            dataGridView1.ColumnCount = ds.Tables[tableName].Columns.Count;
            dataGridView1.ColumnHeadersVisible = true;

            // Set the column header style.
            DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

            columnHeaderStyle.BackColor = Color.Beige;
            columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
            dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

            // Set the column header names.
            string[] fieldTitle = fieldNames;

            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                dataGridView1.Columns[i].Name = fieldTitle[i];
            }

            // Populate the dataset rows. 
            string[,] table = new string[ds.Tables[tableName].Rows.Count, ds.Tables[tableName].Columns.Count];

            for (int i = 0; i < ds.Tables[tableName].Rows.Count; i++)
            {
                for (int k = 0; k < ds.Tables[tableName].Columns.Count; k++)
                {
                    table[i, k] = Convert.ToString(ds.Tables[tableName].Rows[i][k]);
                }
            }

            //Populate the DataGridView with dataset rows.
            var rowCount = table.GetLength(0);
            var rowLength = table.GetLength(1);

            for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex)
            {
                var row = new DataGridViewRow();

                for (int columnIndex = 0; columnIndex < rowLength; ++columnIndex)
                {
                    row.Cells.Add(new DataGridViewTextBoxCell()
                    {
                        Value = table[rowIndex, columnIndex]
                    });
                }

                dataGridView1.Rows.Add(row);
            }

            //Close the Database Connection
            connection.Close();


        }
        catch (OleDbException exp)
        {
            MessageBox.Show("Database Error:" + exp.Message.ToString());
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void CustomerButton_Click(object sender, EventArgs e)
    {
        {
            // Define table to use
            string nameOfTable = "Customer";

            // Define field names
            string[] fieldNames = new string[] { "Cust. ID" , "Timestamp" , "Name" , "Street" , "City" , "State" , "ZIP" , "Telephone" , "Email" , "Balance" };

            // Send data to DataGridView
            InitializeDataGridView(nameOfTable, fieldNames);

            insertButton.Text = "New Customer";
            updateButton.Text = "Update Selected";
            deleteButton.Text = "Delete Selected";
        }
    }

    private void EmployeeButton_Click(object sender, EventArgs e)
    {
        string nameOfTable = "Employee";
        string[] fieldNames = new string[] { "Emp. ID", "Timestamp", "Name", "Street", "City", "State", "ZIP", "Telephone", "Email", "Department" , "Manager" };
        InitializeDataGridView(nameOfTable, fieldNames);
    }

    private void InventoryButton_Click(object sender, EventArgs e)
    {
        string nameOfTable = "Inventory";
        string[] fieldNames = new string[] { "Item ID", "Created", "Updated", "Description", "Price", "Quantity", "Vendor" };
        InitializeDataGridView(nameOfTable, fieldNames);
    }

    private void TransButton_Click(object sender, EventArgs e)
    {
        string nameOfTable = "Transaction";
        string[] fieldNames = new string[] { "Trans. ID", "Timestamp", "Cust. ID", "Item ID", "Emp. ID", "Quantity", "Subtotal", "Tax", "Total" };
        InitializeDataGridView(nameOfTable, fieldNames);
    }

    private void VendorButton_Click(object sender, EventArgs e)
    {
        string nameOfTable = "Vendor";
        string[] fieldNames = new string[] { "Vendor ID", "Timestamp", "Name", "Street", "City", "State", "ZIP", "Telephone", "Email", "Products" };
        InitializeDataGridView(nameOfTable, fieldNames);
    }

    private void insertButton_Click(object sender, EventArgs e)
    {
        if (insertButton.Text == "New Customer")
        {
            var Info = new CustomerInfo();
            Info.Text = "New Customer";
            Info.ShowDialog();
            if (Info.DialogResult == DialogResult.OK)
            {
                string custname = Info.ReturnValue1;            //values preserved after close
                string dateString = Info.ReturnValue2;
                string street = Info.ReturnValue3;
                string city = Info.ReturnValue4;
                string state = Info.ReturnValue5;
                string zip = Info.ReturnValue6;
                string phone = Info.ReturnValue7;
                string email = Info.ReturnValue8;
                string balance = Info.ReturnValue9;

                MessageBox.Show(custname + " " + dateString + " " + street + " " + city + " " + state + " " + zip + " " + phone + " " + email + " " + balance);

                //int cellselected = Convert.ToInt32(dataGridView1.CurrentCell.Selected);
                String connectionString =
                       @"Provider=Microsoft.ACE.OLEDB.12.0;Data"
                     + @" Source=C:\Users\cryow_000\Desktop\AhamblinLarrys1.accdb";
                String tableName = "Customer";

                OleDbConnection connection = new OleDbConnection(connectionString);

                OleDbCommand cmd = new OleDbCommand("INSERT INTO Customer([timestamp],[cust_name],[street],[city],[zip],[state],[telephone],[email],[balance]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", connection);

                cmd.Parameters.AddWithValue("@timestamp", OleDbType.DBTimeStamp).Value = dateString;
                cmd.Parameters.AddWithValue("@cust_name", OleDbType.Char).Value = custname;
                cmd.Parameters.AddWithValue("@street", OleDbType.Char).Value = street;
                cmd.Parameters.AddWithValue("@city", OleDbType.Char).Value = city;
                cmd.Parameters.AddWithValue("@state", OleDbType.Char).Value = state;
                cmd.Parameters.AddWithValue("@zip", OleDbType.Numeric).Value = zip;
                cmd.Parameters.AddWithValue("@telephone", OleDbType.Char).Value = phone;
                cmd.Parameters.AddWithValue("@email", OleDbType.Char).Value = email;
                cmd.Parameters.AddWithValue("@balance", OleDbType.Currency).Value = street;

                cmd.Connection = connection;
                connection.Open();
                cmd.ExecuteNonQuery();
                System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                // Define field names
                string[] fieldNames = new string[] { "Cust. ID", "Timestamp", "Name", "Street", "City", "State", "ZIP", "Telephone", "Email", "Balance" };

                // Send data to DataGridView
                InitializeDataGridView(tableName, fieldNames);

            }

        }

    }


}
}

【问题讨论】:

  • 除了已经提到的排序问题,您将@balance 值设置为street 变量,这将导致类型不匹配。此外,这不是一个真正的问题,但使用.AddWithValue 那样,您将参数的实际值设置为指定的类型,然后使用.Value 将其设置为变量值。只需使用.AddWithValue("@balance", balance);

标签: c# database ms-access oledb


【解决方案1】:

嘿,这通常意味着您尝试插入数据库字段的数据类型与它在数据库中声明为数据类型的数据类型不同。例如,尝试将诸如“hello”之类的字符串插入到数据库中的整数字段中,例如金额。

例如(请原谅写意sql不好)INSERT INTO Transaction(amount) VALUES ("HELLLO") 没有意义,因为您已将交易量减速为整数并尝试将字符串插入其中。

               "INSERT INTO Customer([timestamp],[cust_name],[street],[city],[zip],[state],[telephone],[email],[balance]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", connection);

因此,正如上面答案中提到的,插入的参数类型不匹配,因此请检查插入语句中的所有内容是否正确,顺序是否正确。

【讨论】:

  • ? 是使用OleDb 时所需的参数占位符。命名参数不起作用。
  • 感谢 MrBlue - 从未使用过 OleDb,但每天都在学习一些东西 :) - 已相应地进行了编辑。
【解决方案2】:

问题几乎可以肯定是您为插入指定参数的顺序。似乎 OleDbCommand 不支持命名参数,因为这是执行此操作的常用方法。相反,实际订单很重要。这可能会导致无法引用您认为的自己的问题。

您的插入内容是: [timestamp],[cust_name],[street],[city],[zip],[state],[telephone],[email],[balance]

但是参数是:

@timestamp @cust_name @street @city @state @zip @telephone @email @balance

导致numeric转换成char反之数据类型不匹配问题。

MSDN article about this crazy ordering neccessity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2019-08-05
    • 2013-05-06
    相关资源
    最近更新 更多