简体   繁体   English

C#“当将数据集的日期添加到数据库时,条件表达式中的数据类型不匹配

[英]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. 使用“选择文件..”按钮将CSV文件成功加载到dataGridView1。 When I subsequently click "Submit ..." button3, I am getting an error: 当我随后单击“提交...”按钮3时,出现错误:

Additional information: Data type mismatch in criteria expression. 附加信息:条件表达式中的数据类型不匹配。

Note my Access DB's first column is an auto-numbering Primary Key. 请注意,我的Access DB的第一列是自动编号的主键。 Not sure if that matters here. 不确定在这里是否重要。

Again, I must stress, the CSV loads perfectly, as you can see. 再次强调一下,正如您所见,CSV完美加载。 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. “ Date Filled”列已更改为“ Date_Filled”,因此,由于图像已使用了几天,因此请不要在图中注意。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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