Table of Contents
一、创建.mdb数据库
三、读出数据库的值——C#界面显示表格datagridview
Home Database Mysql Tutorial C#读写Access数据库、表格datagridview窗体显示代码实例

C#读写Access数据库、表格datagridview窗体显示代码实例

Jun 07, 2016 pm 03:49 PM
access datagridview database sheet Read and write

C# 读写 Access 数据库、表 datagridview 窗体显示代码实例 最近项目中用到 C# 对于 Access 数据库表读写 .mdb 操作,学习了下相关的东西,这里先整理 C# 对于 Access 数据库的操作,对于 MySQL 和 Oracle 数据库的操作放到后面再写。 Access 是微软数据库编

C#读写Access数据库、表格datagridview窗体显示代码实例

最近项目中用到C#对于Access数据库表读写.mdb操作,学习了下相关的东西,这里先整理C#对于Access数据库的操作,对于MySQLOracle数据库的操作放到后面再写。

Access是微软数据库编辑软件,其生成的数据库文件为.mdb.accdb,因此在Visual Studio里不像操纵MySQL那样需要使用mysql数据库驱动,系统库里有关于操纵数据库的几个类。说下其中几个主要用到的类:

System.Data;

System.Data.OleDb;

System.Data.Odbc;

System.Data.SqlClient;

 

先简单说下C#对于Access数据库的几个基本操作原理:

 

C#操作Access连接字符串

String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=mydata.mdb";

 

C#操作Access建立连接

OleDbConnection connection = new OleDbConnection(connectionString);

 

C#操作Access使用OleDbCommand类执行Sql语句

OleDbCommand cmd = new OleDbCommand(sql, connection);

connection.Open();

cmd.ExecuteNonQuery();

 

[1]连接Access数据库

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Application.StartupPath + "\\mydata.mdb");

[2]连接SQL Server2000数据库

SqlConnection conn = new SqlConnection("server=.; uid=admin; pwd=123456; database=mydata");

[3]受信任的SQL Server2000数据库

SqlConnection conn = new SqlConnection("workstation id=localhost; Integrated Security=SSPI; database=mydata");

[4]ASP中链接SQL Server/Access数据库:(网页)

(SQL Server):

       conn.connectionstring = "driver={sql server}; server=(local); uid=admin; pwd=123456; database=mydata"

(Access):

conn.connectionstring = "Driver={Microsoft Access Driver(*.mdb)}; DBQ=" & Server.Mappath("mydata.mdb")

!!!注意:→在asp中,语句结束不需要" ; "

--------------------------------------------------------------------------------------------------------------------------------------------

一、创建.mdb数据库

//创建.mdb,注意参数path是.mdb的完整路径(不包含表的名称)
//C#的ADO.NET不能通过编程方式创建新的ACCESS(MDB)数据库,所以只能用COM的链接库的ADOX操作
public static bool CreateMdbDatabase(string path)
{
    try
    {
       ADOX.CatalogClass cat = new ADOX.CatalogClass();
       cat.Create("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";");
       cat = null;
       return true;
    }
    catch
    {
       return false;
    }
}
Copy after login


二、C#写入记录到Access数据库

Sql插入数据库操作,一次只能插入一条记录,多条记录插入只能通过"循环"实现,效率不高;

或者要么更快地就是开启事务(保证数据一致性)→循环插入→最后数据再一起导入。

【实例】在Form上创建一个textbox和一个button,点击buttontextbox中的数据写入到access数据库中。

1.首先创建一个空Access数据库datainput.mdb并写入相应字段:

C#读写Access数据库、表格datagridview窗体显示代码实例

2.读写数据库时应当将数据库关闭,再运行程序进行写操作

using System.Data.Oledb;
private void button1_Click(object sender, EventArgs e)
{
foreach (IACell cell in m_DistributedCells)
{
   //把cell.FrequencyBand、cell.UlFrequency、cell.DlFrequency全部写入数据库表.mdb里去
  //string sql_0 = "insert into table (column1,column2) values('" + textbox.Text + "','" + textbox.Text +"')"; //构造sql语句
   string sql = "";
   if (cell.ChannelIndex == 1)
  {
      sql = "insert into datawrite(ChannelIndex, BandWidth, StartChIndex, EndChIndex, ExcludedChannels, UlFrequency, DlFrequency, ACIR) values('" + 1 + "','" + 20 + "','" + 0 + "','" + 1 + "','" + 1 + "','" + 2402 + "','" + 2422 + "','" + 0 + "')";
   }
   else if (cell.ChannelIndex == 6)
   {
     sql = "insert into datawrite(ChannelIndex, BandWidth, StartChIndex, EndChIndex, ExcludedChannels, UlFrequency, DlFrequency, ACIR) values('" + 6 + "','" + 20 + "','" + 5 + "','" + 6 + "','" + 6 + "','" + 2427 + "','" + 2447 + "','" + 0 + "')";
   }
   else if (cell.ChannelIndex == 11)
  {
     sql = "insert into datawrite(ChannelIndex, BandWidth, StartChIndex, EndChIndex, ExcludedChannels, UlFrequency, DlFrequency, ACIR) values('" + 11 + "','" + 20 + "','" + 10 + "','" + 11 + "','" + 11 + "','" + 2452 + "','" + 2472 + "','" + 0 + "')";
  }
//access数据库路径,注意一定是双斜杠\\,否则会被当成转义字符! 
string dbpath = "D:\\data\\datainput.mdb";
//定义数据库连接对象
  OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + dbpath);
  OleDbCommand cmd = new OleDbCommand(sql, con); //定义Command对象
  con.Open(); //打开数据库连接
  cmd.ExecuteNonQuery(); //执行Command命令
  con.Close(); //关闭数据库连接
 }
}
Copy after login
运行程序,点击button后(断点只循环1次),再次打开刚才的数据库表,此时表里已插入1条记录。

 C#读写Access数据库、表格datagridview窗体显示代码实例


三、读出数据库的值——C#界面显示表格datagridview

【实例】将现有Access数据库表格内的数据以datagridview的形式显示在C#窗体中。

1.现有的数据库,50条记录。

2.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; //主要是这个东西,其实已经包含在System.Data类里了,这里特别提出来注明下
namespace text01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            OleDbConnection thisConnection = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\dataread.mdb");
            string sql = "select * from dataread";
            OleDbDataAdapter thisAdapter = new OleDbDataAdapter(sql, thisConnection);
            System.Data.DataSet thisDataSet = new System.Data.DataSet();
            thisAdapter.Fill(thisDataSet, "table");
            DataTable dt = thisDataSet.Tables["table"];
            this.dataGridView1.DataSource = dt;
            thisConnection.Close();
        }
    }
}
Copy after login

效果图:

C#读写Access数据库、表格datagridview窗体显示代码实例

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

What are the benefits of multithreading in c#? What are the benefits of multithreading in c#? Apr 03, 2025 pm 02:51 PM

The advantage of multithreading is that it can improve performance and resource utilization, especially for processing large amounts of data or performing time-consuming operations. It allows multiple tasks to be performed simultaneously, improving efficiency. However, too many threads can lead to performance degradation, so you need to carefully select the number of threads based on the number of CPU cores and task characteristics. In addition, multi-threaded programming involves challenges such as deadlock and race conditions, which need to be solved using synchronization mechanisms, and requires solid knowledge of concurrent programming, weighing the pros and cons and using them with caution.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use sql if statement How to use sql if statement Apr 09, 2025 pm 06:12 PM

SQL IF statements are used to conditionally execute SQL statements, with the syntax as: IF (condition) THEN {statement} ELSE {statement} END IF;. The condition can be any valid SQL expression, and if the condition is true, execute the THEN clause; if the condition is false, execute the ELSE clause. IF statements can be nested, allowing for more complex conditional checks.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to solve the 'Network Error' caused by Vue Axios across domains How to solve the 'Network Error' caused by Vue Axios across domains Apr 07, 2025 pm 10:27 PM

Methods to solve the cross-domain problem of Vue Axios include: Configuring the CORS header on the server side using the Axios proxy using JSONP using WebSocket using the CORS plug-in

Is there a mac version of mysql Is there a mac version of mysql Apr 08, 2025 pm 02:30 PM

Question: Can MySQL run on macOS? Answer: Yes. Specific instructions: It can be installed through the official MySQL installer. You can use Homebrew to install, providing command-line-driven installation methods and dependency management. Create databases and tables using the MySQL command line client. Optimize query performance and understand indexing, query cache and database standardization. Avoid conflicting version issues and use a single installation method. Ensure secure configuration, use strong passwords and access controls.

See all articles