1. 程式人生 > >C#實用技巧:建立並操作access資料庫(可無密,也可加密)

C#實用技巧:建立並操作access資料庫(可無密,也可加密)

需求

        C#使用小型資料庫,access和sqlite是首選,推薦使用access,可操作,建表視覺化,最大的好處在於可以加密。

說明

        access資料庫是office辦公套件裡的Access建立的,依據office版本不同建立的資料庫有多種字尾名,如下圖:

   

       為了版本通用統一建立字尾名為.mdb(與access2000相容)的資料庫檔案。(電腦未裝access的,需要裝一下access,要用其建立資料庫)。

建立access資料庫

  • 步驟一:開啟access,建立空白資料庫

    

  • 步驟二:設計建立表

      可建資料格式如下左圖,我們見表如下右圖,並將該資料庫儲存為students.mdb

       

     

  • 步驟三:儲存為stduents.db

   

使用vs獲取access連線字串

  • 步驟一:使用vs工具獲取連線字串

        

       

  • 步驟二:點選下一步,選擇資料庫檔案的檔案(此處未設密碼保護,也可設定密碼保護,請自行百度,若設定了密碼保護,則需要填入密碼,使用者名稱無所謂),左圖為未設定密碼的,右圖為設定密碼保護的:

            

  • 步驟三:點選“測試連線”,如下圖:

      

  • 步驟四:點選“高階”,如下圖紅矩形內的,就是我們要的連線字串(設定密碼和未設定密碼的連線字串是一樣的,但是在C#連線時,需要加上密碼,access資料庫密碼登陸無所謂使用者名稱)

      

Provider=Microsoft.Jet.OLEDB.4.0; 
Data Source=D:\wpfproject\Demo16\Demo16\bin\Debug\students.mdb

  加密的字串(包含密碼),驗證可以連線上加密的access資料庫

Provider=Microsoft.Jet.OLEDB.4.0; 
Data Source=D:\wpfproject\Demo16\Demo16\bin\Debug\students.mdb; 
Jet OLEDB:Password=a1234567

  加密的字串(包含使用者名稱和密碼)驗證可以連線上加密的access資料庫

Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=D:\wpfproject\Demo16\Demo16\bin\Debug\students.mdb;
User Id=Admin; 
Jet OLEDB:Password=a1234567

C#操作access資料庫(包括非加密和加密)

  操作程式碼如下:

_accessServer = new AccessServer();
_accessServer.DataBaseName = "students_.mdb";
_accessServer.PASSWORD = "a1234567";
_accessServer.connectToAccess();
string cmd = "";
// 建表,Access通過vs2017驗證,報不支援create table sql語句,但是實際見表成功
// 具體細節,還需要進一步研究
//cmd = "CREATE TABLE student2(" +
        //"no VARCHAR(2) NOT NULL," +
        //"name VARCHAR(12) NOT NULL," +
        //"age INT NOT NULL)";
//if (!_accessServer.doQuery(cmd))
//{
    //MessageBox.Show(string.Format("執行失敗:{0}", cmd), "錯誤");
//}
// 插入資料
cmd = "INSERT INTO student VALUES('4','yang4',34,'2018-03-04')";
if (!_accessServer.doQuery(cmd))
{
    MessageBox.Show(string.Format("執行失敗:{0}", cmd), "錯誤");
}
cmd = "INSERT INTO student VALUES('5','yang4',35,'2018-03-05')";
if (!_accessServer.doQuery(cmd))
{
    MessageBox.Show(string.Format("執行失敗:{0}", cmd), "錯誤");
}
cmd = "INSERT INTO student VALUES('6','yang4',36,'2018-03-06')";
if (!_accessServer.doQuery(cmd))
{
    MessageBox.Show(string.Format("執行失敗:{0}", cmd), "錯誤");
}
cmd = "SELECT * FROM student";
// 返回資料集
OleDbDataReader rd = _accessServer.doQueryReturnData(cmd);
if (rd == null)
{
    MessageBox.Show(string.Format("執行失敗:{0}", cmd), "錯誤");
}
else
{
    while (rd.Read())
    {
        MessageBox.Show(string.Format("ID:{0}, 姓名:{1}, 年齡:{2}, 日期:{3}",
                        rd["ID"].ToString(), rd["姓名"].ToString(), 
                        rd["年齡"].ToString(), rd["日期"].ToString()), "查詢結果");
    }
}
// 關閉資料庫
_accessServer.disconnectFromAccess();

C#操作Access封裝類程式碼如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo16
{
    class AccessServer
    {
        private bool _connecting = false;
        private OleDbConnection _oleDbConnection = null;
        private string _connectStr = "Provider=Microsoft.Jet.OLEDB.4.0;" 
                    + "Data Source={0};User Id=Admin;Jet OLEDB:Database Password={1};";
        // 資料庫名
        private string _databaseName = "";
        public string DataBaseName { get => _databaseName; set => _databaseName = value; }
        // 資料庫密碼
        private string _password = "";
        public string PASSWORD { get => _password; set => _password = value; }
        public AccessServer()
        {
        }
        // 連線到資料庫
        public bool connectToAccess()
        {
            try
            {
                string connectStr = string.Format(_connectStr, _databaseName, _password);
                _oleDbConnection = new OleDbConnection(connectStr);
                _oleDbConnection.Open();
                _connecting = true;
                return true;
            }
            catch
            {
                return false;
            }
        }
        // 執行資料庫指令(無需返回的)
        public bool doQuery(string cmd)
        {
            if (!_connecting)
            {
                return false;
            }
            try
            {
                OleDbCommand sqlCom = new OleDbCommand(cmd, _oleDbConnection);
                sqlCom.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
        }
        // 執行資料庫指令(返回資料記錄的)
        /*  補充:如何操作 SQLiteDataReader 檢視資料,
         *    SQLiteDataReader只能ToString()
         *    while(oleDbDataReader.Read())
         *    {
         *      string number = dr["ID"].ToString();
         *      string name = dr["姓名"].ToString();
         *      int age = Convert.ToInt32(dr["年齡"].ToString());
         *      string data = dr["日期"].ToString();
         *    }	
        */
        public OleDbDataReader doQueryReturnData(string cmd)
        {
            if (!_connecting)
            {
                return null;
            }
            try
            {
                OleDbCommand sqlCom = _oleDbConnection.CreateCommand();
                sqlCom.CommandText = cmd;
                OleDbDataReader oleDbDataReader = sqlCom.ExecuteReader();
                return oleDbDataReader;
            }
            catch
            {
                return null;
            }
        }
        // 斷開與資料庫的連線
        public void disconnectFromAccess()
        {
            if (!_connecting)
                return;
            try
            {
                _oleDbConnection.Dispose();
                _connecting = false;
            }
            catch
            {
                _connecting = false;
            }
        }
    }
}