使用C#的Microsoft Access和OLEDB在数据库中添加数据 [英] Adding data in the database using microsoft access and OleDb in C#

查看:673
本文介绍了使用C#的Microsoft Access和OLEDB在数据库中添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的业余使用OleDb的图书馆,我想添加一个文本格式的文本框与此库的数据库。
我的代码:

I'm amateur in using of OleDb library and I want to add a text form text box into a database with this library. My code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private OleDbConnection conn = new OleDbConnection();
    private void button1_Click(object sender, EventArgs e)
    {
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Project\Learning\Visual C#\Form\WindowsFormsApplication1\WindowsFormsApplication1\Test.mdb";
        string NAME = textBox1.Text;
        conn.Open();
        OleDbCommand cmmd = new OleDbCommand("INSERT into student(NAME)" + "VALUES(@NAME)", conn);  
        if (conn.State == ConnectionState.Open)
        {
            cmmd.Parameters.Add("@NAME", OleDbType.Char, 20);
            cmmd.Parameters["@NAME"].Value = NAME;
            try
            {
                cmmd.ExecuteNonQuery();
                MessageBox.Show("DATA ADDED");
                conn.Close();
            }
            catch (OleDbException expe)
            {
                MessageBox.Show(expe.Source);
            }
        }
        else
        {
            MessageBox.Show("CON FAILED");
        }
    }
}



但不起作用。
我不能找到为C#的OleDbCommand命令很好的借鉴。
我怎么能在我的代码使用这个命令?

But doesn't work. I cant find good reference for "OleDbCommand" command for C#. How can I use this command in my code?

推荐答案

解决

public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Project\Learning\Visual C#\Form\WindowsFormsApplication2\WindowsFormsApplication2\Test.mdb";
        conn.Open();
        string Name = textBox1.Text;
        OleDbCommand cmmd = new OleDbCommand("INSERT INTO table1 (student) Values(@Name)", conn);
        if (conn.State == ConnectionState.Open)
        {
            cmmd.Parameters.Add("@Name", OleDbType.VarWChar, 20).Value = Name;
            try
            {
                cmmd.ExecuteNonQuery();
                MessageBox.Show("DATA ADDED");
                conn.Close();
            }
            catch (OleDbException expe)
            {
                MessageBox.Show(expe.Message);
                conn.Close();
            }
        }
        else
        {
            MessageBox.Show("CON FAILED");
        }
    }

这篇关于使用C#的Microsoft Access和OLEDB在数据库中添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆