Unity如何连接Sqlit数据库,操作数据库

发表于2017-12-27
评论0 2.3k浏览

连接Sqlite数据库需要sqlite工具,下载对应系统的工具SQLite Download Page和下载sqlite可视化工具(下方百度云)操作Sqlite数据库,通过封装的(增删改查)的类来操作数据库 。


可视化工具和DBAccess类脚本链接:http://pan.baidu.com/s/1mij6z7E

这里用的是Mac系统,数据库的路径不一样,如果是windows系统的朋友需要改一下路径

1.直接对数据库的操作(增删改查)

例 插入数据

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using Mono.Data.Sqlite;  
using System.IO;  
public class ReadConfig : MonoBehaviour {  
    //声明数据库连接对象  
    SqliteCommand sqlCommand;  
    SqliteConnection sqlConection;  
    //定义数据的存储路径  
    private string path;   
    // Use this for initialization  
    void Start () {  
        path="Data Source="+Application.streamingAssetsPath+"/"+"MySql.db";  
        //if (!File.Exists(path))  
        //{  
        //    File.Create(path);  
        //}  
        try  
        {  
            sqlConection = new SqliteConnection(path);  
            sqlConection.Open();  
            print("连接成功");  
            //创建Command  
            sqlCommand=sqlConection.CreateCommand();  
            Insert();  
        }  
        catch(System.Exception e)  
        {  
            Debug.LogError("打开数据库失败"+e.ToString());  
        }  
    }  
    //插入数据  
    public void Insert()  
    {  
//        string item="INSERT INTO"+"PlayerMessager"+"VALUES("1","盖伦"));  
        //一次只能插入一条的数据  
        sqlCommand.CommandText="INSERT INTO "+"PlayerMassager"+" VALUES "+"(567,'小乔','456','456554@qq.com')";  
        //sqlCommand.CommandText="insert into "+"PlayerMassager"+" values "+"(147,'阿狸','753','456645646@QQ.com')";  
//        sqlCommand.CommandText="Insert Into PlayerMassager (ID,Name,PassWord,Emil) values"+"(567,'小乔','456','456554@qq.com')";  
        //执行SQL语句  
        sqlCommand.ExecuteNonQuery();  
        print("插入成功");  
        //释放Command中的资源  
        sqlCommand.Dispose();  
        //关闭数据库  
        sqlConection.Close();  
        print("关闭数据库");  
    }  
}  

数据插入前



数据插入后



2.通过DBAccess类操作数据库

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using Mono.Data.Sqlite;  
public class TestDB : MonoBehaviour {  
    private DbAccess db;  
    private string path;  
    private string tableName;  
    // Use this for initialization  
    void Start () {  
        tableName="PlayerMassager";  
        //Pc端的链接  
        //path = @"Data Source="+ Application.streamingAssetsPath + "/MySql.db";  
        //Mac端的数据库路径  
        path="Data Source="+Application.streamingAssetsPath+"/MySql.db";  
        db = new DbAccess();  
    }  
    public void Open()  
    {  
        db = new DbAccess(path);  
    }  
    //创建表  
    public void CreateTable()  
    {  
        Open();  
        db.CreateTable("Property",new string[]{"Name","WeaponType","attack","mass"},new string[]{"TEXT","TEXT","TEXT","TEXT"});  
        db.CloseSqlConnection();  
    }  
    public void Insert()  
    {  
        //打开数据库  
        Open();  
        //插入数据  
        db.InsertInto(tableName,new string[]{"582","'子涵'","'Love'","'56467664@qq.com'"});  
        db.InsertIntoSpecific(tableName, new string[]{ "ID", "Name" }, new string[]{ "125", "'寒冰'" });  
        db.CloseSqlConnection();  
    }  
    //更新  
    public void UpdateSql()  
    {  
        Open();  
        //更新数据   表名 要更新的键  要跟新的值 条件  
        db.UpdateInto(tableName,new string[]{"PassWord"},new string[]{"'666666666'"},"ID","147");  
        db.CloseSqlConnection();  
    }  
    //读取  
    public void ReadSql()  
    {  
        Open();  
        //读取表内所有数据  
        SqliteDataReader reader=db.ReadFullTable(tableName);  
        //循环表内数据  
        while (reader.Read())   
        {  
            print(reader.GetInt32(reader.GetOrdinal("ID")));  
            print(reader.GetString(reader.GetOrdinal("Name")));  
            print(reader.GetString(reader.GetOrdinal("PassWord")));  
            print(reader.GetString(reader.GetOrdinal("Emil")));  
            //打印这个物体的所有信息  
//            for (int i = 0; i < reader.FieldCount; i++)  
//            {  
//                print(reader.GetName(i));  
//                print(reader.GetValue(i));  
//            }  
        }  
        db.CloseSqlConnection();  
    }  
    //删除表  
    public void RemoveTable()  
    {  
        Open();  
        db.DeleteContents("Property");  
        db.CloseSqlConnection();  
    }  
    //删除一条数据  
    public void DeleteWhere()  
    {  
        Open();  
        db.Delete("Property", new string[]{ "Name" }, new string[]{ "'电刀'" });   
        db.CloseSqlConnection();  
    }  
    //查询  
    public void SeletSql()  
    {  
        Open();  
        //  
        SqliteDataReader reader=db.SelectWhere(tableName,new string[]{"Name"},new string[]{"ID"},new string[]{"=="},new string[]{"582"});  
        while (reader.Read())  
        {  
            print(reader.GetString(reader.GetOrdinal("Name")));  
        }  
        db.CloseSqlConnection();  
    }  
    //显示  
    private void OnGUI()  
    {  
        if (GUI.Button(new Rect(100, 100, 100, 50), "执行"))  
        {  
            UpdateSql();  
        }  
    }  
}  
注意:数据库的路径,添加数据时必须要添加上主键,不然在数据库可视化工具上不显示,每次打开数据库,操作完成就必须关闭数据库,不让会发生死锁

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引