简体   繁体   English

插入数据以使用C#访问数据库

[英]Insert data in to access database with C#

For a program I'm making, I want to add the countrycode, the zipcode of the city and the name of the city in a table. 对于我正在制作的程序,我想在表格中添加国家代码,城市的邮政编码和城市的名称。 If this information is already in the table, nothing needs to happen. 如果此信息已在表中,则无需任何操作。

However, new records won't insert in my table. 但是,新记录不会插入到我的表中。

For example: with only 'BE, '3580', 'Beringen' in my table. 例如:我的表中只有'BE,'3580','Beringen'。 I start my program. 我开始我的程序。 First I insert the values that are already in my table and nothing happends. 首先,我插入表中已经存在的值,但没有任何反应。

Second I try to add a new value (for example: ('BE' '3500', 'Hasselt')). 其次,我尝试添加一个新值(例如:('BE''3500','Hasselt'))。 I get the messagebox with: "Data added succesfully!". 我收到消息框:“数据添加成功!”。

After that, I try to add the same value as before ('BE' '3500', 'Hasselt'). 之后,我尝试添加与以前相同的值(“ BE”,“ 3500”,“ Hasselt”)。 My program does nothing. 我的程序什么也不做。

But when I open Access, to take a look in the table. 但是当我打开Access时,要看一下表。 No new data was added. 没有添加新数据。

What did I do wrong? 我做错了什么?

 connection.ConnectionString = @"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = DeJongDatabase.mdb; Persist Security Info = True";

This is the rest of my code 这是我的其余代码

    static class Zipcodes
{
    public static void checkAndSavePostCode(String country, String zipcode, string city)
    {
        Globals.connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = Globals.connection;
        command.CommandText = string.Format("SELECT * FROM Zipcodes WHERE CountryCode = @countryCode AND City= @city AND Zipcode= @zipcode");
        command.Parameters.AddWithValue("@countyCode", country);
        command.Parameters.AddWithValue("@city", city);
        command.Parameters.AddWithValue("@zipcode", zipcode);
        OleDbDataReader postcodeReader = command.ExecuteReader();
        bool exists = false;

        while (postcodeReader.Read())
        {
            exists = true;
        }
        postcodeReader.Close();
        command.Dispose();
        Globals.connection.Close();

        OleDbCommand writeCommand = new OleDbCommand();
        writeCommand.Connection = Globals.connection;

        try
        {
            Globals.connection.Open();
            if (!exists)
            {
                if (Globals.connection.State == System.Data.ConnectionState.Open)
                {
                    /*writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(@countryCode, @zipcode, @city)";
                    writeCommand.Parameters.AddWithValue("@countyCode", country);
                    writeCommand.Parameters.AddWithValue("@city", city);
                    writeCommand.Parameters.AddWithValue("@zipcode", zipcode); */

                    writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(?, ?, ?)";
                    writeCommand.Parameters.Add(new OleDbParameter("@countryCode", OleDbType.VarChar)).Value = country;
                    writeCommand.Parameters.Add(new OleDbParameter("@zipcode", OleDbType.VarChar)).Value = zipcode;
                    writeCommand.Parameters.Add(new OleDbParameter("@city", OleDbType.VarChar)).Value = city;

                    if (writeCommand.ExecuteNonQuery() > 0)
                    {
                        MessageBox.Show("Data saved successfuly...!");
                    }
                }
                else
                {
                    MessageBox.Show("FAILED");
                }
            }
        }
        catch(OleDbException ex)
        {
            MessageBox.Show(ex.Source);
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            Globals.connection.Close();
        }

This works fine for me. 这对我来说很好。

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 WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            OleDbConnection conn;
            conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\your_path_here\Northwind.mdb");

            conn.Open();

            OleDbCommand cmd = conn.CreateCommand();

            cmd.CommandText = @"INSERT INTO MyExcelTable([Fname], [Lname],  [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
            cmd.ExecuteNonQuery();
            conn.Close();

        }

        public OleDbConnection myCon { get; set; }

        private void button2_Click(object sender, EventArgs e)
        {

            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";

            string fstName  = textBox1.Text.Trim();
            string lstName  = textBox2.Text.Trim();
            string adres = textBox3.Text.Trim();
            OleDbCommand cmd = new OleDbCommand(@"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (@FName, @LName, @Address)")
            {
                Connection = conn
            };

            conn.Open();

            if (conn.State == ConnectionState.Open)
            {
                // you should always use parameterized queries to avoid SQL Injection
                cmd.Parameters.Add("@FName", OleDbType.VarChar).Value = fstName;
                cmd.Parameters.Add("@LName", OleDbType.VarChar).Value = lstName;
                cmd.Parameters.Add("@Address", OleDbType.VarChar).Value = adres;

                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show(@"Data Added");
                    conn.Close();
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Source + "\n" + ex.Message);
                    conn.Close();
                }
            }
            else
            {
                MessageBox.Show(@"Connection Failed");
            }
        }
        }
    }

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

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