使用C#插入Access DB

时间:2014-03-31 03:20:59

标签: c# database ms-access oledb

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

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

            }

        }

    }


}
}

2 个答案:

答案 0 :(得分:1)

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

您的插入内容如下: [时间戳],[CUST_NAME],[街道],[城市]的 [拉链],[状态] 下,[电话],[电子邮件],[平衡] < / p>

但参数是:

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

将数字导入char,反之亦然数据类型不匹配问题。

MSDN article about this crazy ordering neccessity

答案 1 :(得分:0)

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

例如(原谅可怜的写意sql)INSERT INTO Transaction(amount) VALUES ("HELLLO") 没有意义,因为你将事务量减少为整数并试图在其中插入一个字符串。

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

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