简体   繁体   中英

C# "Data type mismatch in criteria expression, when adding date from dataset to database

Successfully loading a CSV file to the dataGridView with the "Choose file .." button1. When I subsequently click "Submit ..." button3, I am getting an error:

Additional information: Data type mismatch in criteria expression.

Note my Access DB's first column is an auto-numbering Primary Key. Not sure if that matters here.

Again, I must stress, the CSV loads perfectly, as you can see. The "Date Filled" column has been changed to "Date_Filled", so pay no attention to that, in the image, as it's a couple days old.

Here is my code, along with a screenshot. ALL help is greatly appreciated!

在此处输入图片说明

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.IO;
using System.Globalization;
using System.Configuration;
using System.Data.OleDb;

namespace csvToGrid
{
    public partial class Import : Form
        {
            DataSet dataset;
        }
    public partial class Import : Form
        {
            public Import()
                {
                    InitializeComponent();
                }
        public void button1_Click(object sender, EventArgs e)
            {
                string delimiter = ",";
                string tablename = "medTable";
                dataset = new DataSet();
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                filename = openFileDialog1.FileName;
                                StreamReader sr = new StreamReader(filename);
                                string csv = File.ReadAllText(openFileDialog1.FileName);
                                dataset.Tables.Add(tablename);
                                dataset.Tables[tablename].Columns.Add("Prescription");
                                dataset.Tables[tablename].Columns.Add("Customer_Name");
                                dataset.Tables[tablename].Columns.Add("Medication");
                                dataset.Tables[tablename].Columns.Add("Quantity");
                                dataset.Tables[tablename].Columns.Add("Date_Filled");

                                string allData = sr.ReadToEnd();
                                string[] rows = allData.Split("\r".ToCharArray());

                                foreach (string r in rows)
                                    {
                                        string[] items = r.Split(delimiter.ToCharArray());
                                        dataset.Tables[tablename].Rows.Add(items);
                                    }
                                this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
                                MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
                            }
                        else
                            {
                                this.Close();
                            }
                }
            }

        public string filename { get; set; }


        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
            {

            }

        private void Import_Load(object sender, EventArgs e)
            {

            }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)

            //remove the semicolon, and add brackets below after line
            {

                var AccessCnn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", @"C:\Search\KinneyDatabase.accdb");

                using (OleDbConnection accessCnn = new OleDbConnection(AccessCnn))
                {
                    //Create The Command
                    var accessCmd = new OleDbCommand(@"INSERT INTO script_Orders (script,cust_Name,drug,qty,fill_Date) VALUES (@Prescription, @Customer_Name, @Medication, @Quantity, @Date_Filled)", accessCnn);

                    OleDbParameter d = accessCmd.CreateParameter();
                    d.OleDbType = OleDbType.Date;

                    foreach (var row in dataset.Tables["medTable"].Rows)

                    {
                        accessCmd.Parameters.Clear();
                        accessCmd.Parameters.AddWithValue(@"Prescription","script");
                        accessCmd.Parameters.AddWithValue(@"Customer_Name", "cust_Name");
                        accessCmd.Parameters.AddWithValue(@"Medication", "drug");
                        accessCmd.Parameters.AddWithValue(@"Quantity", "qty");
                        accessCmd.Parameters.AddWithValue(@"Date_Filled", "fill_Date");
                        accessCnn.Open();
                        accessCmd.ExecuteNonQuery();
                        accessCnn.Close();
                    }
                }
            }
        }
    }

在此处输入图片说明

I will try with this:

accessCnn.Open();
foreach (var row in dataset.Tables["medTable"].Rows)
{
    accessCmd.Parameters.Clear();
    accessCmd.Parameters.AddWithValue("@Prescription",row["script"].ToString());
    accessCmd.Parameters.AddWithValue("@Customer_Name", row["cust_Name"].ToString());
    accessCmd.Parameters.AddWithValue("@Medication", row["drug"].ToString());
    accessCmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row["qty"]));
    accessCmd.Parameters.AddWithValue("@Date_Filled", Convert.ToDate(row["fill_Date"]));
    accessCmd.ExecuteNonQuery();
}
accessCnn.Close();

Also, you could try to optimize the query creating the parameters before entering the loop and inside the loop changing only the value without destroying them and recreating them for every loop

accessCmd.Parameters.Add("@Prescription", OleDbType.VarChar , 80);
accessCmd.Parameters.Add("@Customer_Name", OleDbType.VarChar, 80);
accessCmd.Parameters.Add("@Medication", OleDbType.VarChar, 80);
accessCmd.Parameters.Add("@Quantity", OleDbType.Integer);
accessCmd.Parameters.Add("@Date_Filled", OleDbType.Date);

accessCnn.Open();
foreach (var row in dataset.Tables["medTable"].Rows)
{
    accessCmd.Parameters["@Prescription"].Value = row["script"].ToString();
    accessCmd.Parameters["@Customer_Name"].Value = row["cust_Name"].ToString();
    accessCmd.Parameters["@Medication"].Value = row["drug"].ToString();
    accessCmd.Parameters["@Quantity"].Value = Convert.ToInt32(row["qty"]);
    accessCmd.Parameters["#Date_Filled"].Value = Convert.ToDate(row["fill_Date"]);
    accessCmd.ExecuteNonQuery();
}
accessCnn.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM