首先,准备工作:
-
创建一个Access 数据库,命名AccessTest.accdb,添加一些数据用于测试
-
准备System.Data.dll与System.EnterpriseServices.dll两个插件,这是访问Access数据需要引用的dll
-
如果完成后需要在其他电脑上访问,并且该电脑没有安装Office,就可以要求他安装access访问组件,然后就可以运行了,所有的相应组件与代码,后面都会给一个网盘链接
然后开始创建Unity工程
1.在unity工程文件夹Assets同级目录下创建一个SQLData文件夹用来存放Access数据库文件AccessTest.accdb
2.在unity工程文件夹Assets目录下创建一个Plugins文件夹用来存放System.Data.dll与System.EnterpriseServices.dll两个dll文件
3.创建一个功能脚本AccessData.cs,用来访问Access数据库
using System.Data.Odbc; using System.Data; using System; /**************************************** * 功能:访问access数据库. * 创建: 2015-10-19 _D * * *************************************/ public class AccessData { /// <summary> /// 本类对象 /// </summary> private static AccessData accessData; /// <summary> /// 连接对象 /// </summary> private OdbcConnection con; /// <summary> ///初始化并返回本类对象 /// </summary> /// <returns></returns> public static AccessData getInstance() { if (accessData == null) { accessData = new AccessData(); accessData.con = new OdbcConnection(); } return accessData; } /// <summary> /// 数据库连接函数 /// </summary> /// <param name="accessPath">access数据库路径</param> public void Connection(string accessPath) { string connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + accessPath; con.ConnectionString = connection; try { if(con.State==ConnectionState.Closed) con.Open(); } catch (Exception e) { throw new Exception(e.Message); } } /// <summary> /// 断开与数据库的连接 /// </summary> public void Colse() { if (con.State != ConnectionState.Closed) { con.Close(); } } /// <summary> /// 操作数据库 /// </summary> /// <param name="sql">sql语句</param> /// <param name="dataTableName">返回的DataTable的名称</param> /// <returns></returns> public DataTable OperateAccess(string sql, string dataTableName) { OdbcCommand cmd = new OdbcCommand(sql,con); DataTable dt = new DataTable(dataTableName); OdbcDataReader reader = cmd.ExecuteReader(); dt.Load(reader); reader.Close(); return dt; } }4.创建一个测试脚本Test.cs,用来具体操作Access数据库
using UnityEngine; using System.Collections; using System.Data; public class Test : MonoBehaviour { /// <summary> /// Access数据库路径 /// </summary> private string accessPath; // Use this for initialization void Start () { accessPath = Application.dataPath; int num=accessPath.LastIndexOf("/"); accessPath = accessPath.Substring(0, num); accessPath += "/SQLData/AccessTest.accdb"; AccessData.getInstance().Connection(accessPath); } string text = ""; // Update is called once per frame void OnGUI () { if (GUI.Button(new Rect(0, 0, 100, 30), "查询")) { string sql = "select * from t_First"; DataTable dt = AccessData.getInstance().OperateAccess(sql, "select_t_First"); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { text +=dt.Columns[j].ColumnName + ":" + dt.Rows[i][dt.Columns[j].ColumnName]+" "; } text += " "; } } GUI.Label(new Rect(0, 60, 200, 60), text); } }5.将Test脚本绑定在场景物体中,运行测试