简体   繁体   English

在C#中将记录插入Microsoft Access数据库

[英]Inserting records into a Microsoft Access database in C#

I am inserting data to access 2000-2003 file format database using C#. 我使用C#插入数据以访问2000-2003文件格式数据库。 When I had a database with 2 fields the query works fine, but when there are more fields its is not working. 当我有一个包含2个字段的数据库时,查询工作正常,但是当有更多字段时,它不起作用。

I have identical code for both and I am not able to find the problem. 我有两个相同的代码,我无法找到问题。

using System.Data.OleDb;    // By using this namespace I can connect to the Access Database.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private OleDbConnection myconn;
        public Form1()
        {
            InitializeComponent();
            myconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\NewManageContacts.mdb");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
           // this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
            // TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
            this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);

        }


        private void button1_Click(object sender, EventArgs e)
        {
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
           // string query = "insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
            cmd.CommandText = @"insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text +  "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
            cmd.Connection = myconn;
            myconn.Open();
            cmd.ExecuteNonQuery();
            System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            myconn.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
            textBox8.Text = "";

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

    }
}

This is the code for the table with just 2 fields 这是只有2个字段的表的代码

public partial class Form1 : Form
{
    private OleDbConnection myCon;
    public Form1()
    {
        InitializeComponent();
        myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\Database1.mdb");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'database1DataSet.Table1' table. You can move, or remove it, as needed.
        this.table1TableAdapter.Fill(this.database1DataSet.Table1);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into Table1 (name,fname) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
        cmd.Connection = myCon;
        myCon.Open();
        cmd.ExecuteNonQuery();
        System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
        myCon.Close();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        textBox2.Text = "";
    }
}

The extra fields you are trying to insert probably have values that don't readily concatenate into a valid SQL statement. 您尝试插入的额外字段可能具有不容易连接到有效SQL语句的值。 For instance: 例如:

string field1 = "meh";
string field2 = "whatever";
string field3 = "'Ahoy!' bellowed the sailor.";
var cmd = new SqlCommand(
    "INSERT INTO blah (x, y, z) VALUES ('" + field1 + "', '" + field2 + "', '" + field3 + '")");

Imagine what the concatenated SQL will look like, given the above input. 想象一下,在给定上述输入的情况下,连接的SQL将是什么样子。

Worse, imagine the SQL you'll be executing if someone types this into your form: 更糟糕的是,想象一下如果有人在你的表单中输入这个SQL,你将执行它:

field3 = "Bobby'); DROP TABLE Users; -- ";

Use parameterised queries via cmd.Parameters.Add or AddRange (described here ). 通过cmd.Parameters.AddAddRange此处描述)使用参数化查询。 The above example might be emended thus: 因此可以修改上面的例子:

var cmd = new SqlCommand("INSERT INTO blah (x, y, z) VALUES (@x, @y, @z)");
cmd.Parameters.AddRange(new[] {
    new SqlParameter("@x", field1),
    new SqlParameter("@y", field2),
    new SqlParameter("@z", field2)
    });

If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. 如果您正在使用数据库,那么主要是借助try-catch块语句,这将有助于指导您的代码。 Here i am showing you that how to insert some values in Data Base with a Button Click Event. 在这里,我向您展示如何使用Button Click事件在数据库中插入一些值。

 private void button2_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";

     try
       {
           conn.Open();
           String ticketno=textBox1.Text.ToString();                 
           String Purchaseprice=textBox2.Text.ToString();
           String sellprice=textBox3.Text.ToString();
           String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";

            OleDbCommand cmd = new OleDbCommand(my_querry, conn);
            cmd.ExecuteNonQuery();

            MessageBox.Show("Data saved successfuly...!");
          }
         catch (Exception ex)
         {
             MessageBox.Show("Failed due to"+ex.Message);
         }
         finally
         {
             conn.Close();
         }

this code for public: 这段代码适用于公众:

        OleDbConnection con = new OleDbConnection(@"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Mohammadhoseyn_mehri\Documents\Data.mdb");

this code for singup button: 这个代码为singup按钮:

 try
        {

                craeteaccount();
            else
            {
                MessageBox.Show("Please re Enter Your PassWord");
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            MessageBox.Show("Data saved successfuly...!");
            con.Close();
        }

this code for create account method: 这个代码用于创建帐户方法:

OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Login", con);
        con.Open();
        String ticketno = textBox2.Text.ToString();
        String Purchaseprice = textBox1.Text.ToString();
        String my_querry = $"INSERT INTO Login(username,pass)VALUES('{ticketno}','{Purchaseprice}')";

        OleDbCommand cmd = new OleDbCommand(my_querry, con);
        cmd.ExecuteNonQuery();
private void btnSave_Click(object sender, EventArgs e)**
{
   OleDbCommand cmd = new OleDbCommand();
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = @"insert into Personal (P_name, P_add,P_Phone)VALUES('" + txtName.Text + "','" +txtAddress.Text + "','" + txtPhone.Text + "')";
   cmd.Connection = con;
   con.Open();
   cmd.ExecuteNonQuery();
   System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
   con.Close();
   txtName.Text = "";
   txtAddress.Text = "";
   txtPhone.Text = "";
}

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

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