Unity中Sqlite数据库

Unity中Sqlite数据库html

#1SQLite数据库简介

++1.1、什么是SQLitesql

++++1SQLite是一款轻型的数据库。数据库

++++2SQLite的设计目标是嵌入式的。编程

++++3SQLite占用资源很是的低。设计模式

++++4SQLite可以支持Windows/Linux/Unix等等主流的操做系统。服务器


++1.2SQLite安装网络

++++下载地址:iphone

--http://rj.baidu.com/soft/detail/22353.html?ald编辑器

--SQLiteManager学习


++1.3、建立数据库

++++New SQLite Database

 


++1.4、建立数据库表格

 


++1.5、数据预览与操做

 


++1.6、执行SQL语句

 


#2SQL语法(增删改查)

++2.1SQL INSERT INTO语句

++++做用: INSERT INTO 语句用于向表格中插入新的行。

++++语法1INSERT INTO 表名称VALUES(1,2,...)

++++语法2INSERT INTO table_name(1,2,...) VALUES(1,2,...)

++++示例1

    --INSERT INTO Persons VALUES(‘Gates’, ‘Bill’, ‘Xuanwumen 10’, ‘Beijing’)

++++示例2

    --INSERT INTO Persons(LastName, Address) VALUES(‘Wilson’, ‘Champs-Elysees’)


++2.2SQL DELETE语句

++++做用: DELETE语句用于删除表中的行。

++++语法: DELETE FROM Person WHERE LastName =‘Wilson’

++++示例1

    --DELETE FROM Person WHERE LastName = ‘Wilson’

++++示例2

    --DELETE FROM table_name(删除表格全部内容)


++2.3SQL UPDATE语句

++++做用: Update语句用于修改表中的数据。

++++语法: UPDATE 表名称 SET 列名称=新值 WHERE 列名称=某值

++++示例:

    --UPDATE Person SET FirstName = ‘Fred’ WHERE LastName=’Wilson’


++2.4SQL SELECT语句

++++做用: SELECT语句用于从表中选取数据。

++++语法: SELECT 列名称 FROM 表名称

++++示例:

    --SELECT LastName,FirstName FROM Persons


#3SQLite数据库图形化界面使用




#4、 在Unity中使用SQLite数据库

++4.1、准备工做

++++导入mono.data.sqlite.dllAssets文件夹

++++代码添加库: using Mono.Data.Sqlite;


++4.2SQLiteConnection

++++使用SQLiteConnection对象,进行数据库链接,此操做能够建立空的数据库。

++++数据链接:

//数据库链接路径

string path data source= + Application.streamingAssetsPath /UserDatabase.sqlite;

 

void OpenDataBase(string connectionString){

    try{

        conn = new SqliteConnection(connectionString);

        conn.Open();

    }catch(System.Exception exc){

        Debug.Log(exc);

    }

}


++4.3SQLiteCommand

++++使用SqliteCommand数据指令对象进行数据库操做。

++++使用SqliteDataReader数据读取对象,进行数据库内容读取。

++++建表:

//建表

void CreateTable(){

    //判断数据库中是否有UserTable这个表

    SqliteCommand cmd conn.CreateCommand();

    cmd.CommandText select count(*) from sqlite_master where type=table and name=UserTable’”;

    SqliteDataReader reader cmd.ExecuteReader();

 

    //判断数据库中是否存在这张表

    bool isExsit false;

    while(reader.Read()){

        for(inti= 0; i<reader.FieldCounti++){

            if(reader.GetValue(i).ToString() == 1){

                isExsit=true;

            }

        }

    }

 

    //若是表不存在则建表

    reader.Dispose();

    reader.Close();

    reader= null;

 

    if(!isExist){

        Debug.Log(表不存在,建表);

        cmd.CommandText= Create Table UserTable(uname text, pwd text);

        cmd.ExecuteNonQuery();

    }

    cmd.Dispose();

    cmd= null

    CloseDataBase();  //数据库操做完成以后要将数据库关闭

}

 

++++插入数据:

//UserTable表中插入数据

SqliteCommand cmd conn.CreateCommand();

cmd.CommandText insert into UserTable values( +unameInput.text+ , +passwordInput.text+ );

 

try{

    cmd.ExecuteNonQuery()

 

}catch(System.Exception exc){

    Debug.Log(exc);

}


++++4.4SQLiteDataReader

++++使用SqliteDataReader数据读取对象,进行数据库内容读取。

//建立查询的sql语句

string query =  select pwd from UserTable where uname=+  +uname+  ;

SqliteCommand cmd conn.CreateCommand();

cmd.CommandText query;

SqliteDataReader reader cmd.ExecuteReader();  //执行查询操做

 

bool result false;  //标记表中是否有此条数据

while(reader.Read()){

    for(int i =0i<reader.FieldCount;  i++){

        if(reader.GetValue(i).ToString() == pwd){

            //reader.GetValue(i)返回表中某一列所对应的值

            result true; //若是有,就修改标记值

        }

    }

}


++执行SQL语句三种方式

++++1int ExecuteNonQuery()

--返回受影响的行数(经常使用于执行增删改操做)

++++2object ExecuteScalar()

--返回查询到的第一个值(经常使用于只查询一个结果时)

++++3SqliteDataReader ExecuteReader()

    --返回全部查询的结果(SqliteDataReader对象)


#5、 封装数据库管理类

++5.1、为什么要封装?

++++1、方便项目管理

++++2、方便开发人员的快捷的使用

++++3、防止高度保密数据外泄


++5.2、要封装哪些方法?

++++1、链接数据库

++++2、经过Sql语句查询数据

++++3、经过表名查询全表数据

...

++++4、关闭数据库链接,释放资源


++5.3、链接数据库

public class DataBase{

    SqliteConnection conn; //数据库连接对象

 

    public DataBase(string connectionPath){

        ConnectionDB(connectionPath);

    }

 

    //链接数据库

    void ConnectionDB(string connectionPath){

        try{

            conn new SpliteConnection(connectionPath);

            Debug.Log(链接数据库);

        }catch(System.Exception exp){

            Debug.Log(exp);

            throw;

        }

    }

 

    DataBase _db; //Use this for initialization

 

    void Start(){

        string path=null;

    #if UNITY_IPHONE

        path data source= + Application.persistentDataPath +  /UserData.db;

    #elif UNITY_STANDALONE_WIN

        path data source= + Application.streamingAssetsPath  /UserData.db;

    #elif UNITY_ANDROID

        path =  url=file:  + Application.persistentDataPath +  /UserData.db;

    #endif

        _db = new DataBase(path);

    }

}


++5.4、经过Sql语句插入数据

//向某个表中插入数据

public void InsertDatabase(string tableNamestring[] row){

    OpenDataBase(); //打开数据库

    string sql=insert into + tableName +values( + row[0];

    for(int i =1row.Lengthi++){

        sql += ‘’, row[i];

    }

    sql +=  );

    cmd =conn.CreateCommand();

    cmd.CommandText sql;

    cmd.ExecuteNonQuery();

 

    CloseDataBase();  //关闭数据库

}


++5.5、经过Sql语句查询

//经过Sql语句查询,返回查询结果

public SqliteDataReader SelectFromDataBase(string sql){

    try{

        cmd conn.CreateCommand();

        cmd.CommandText sql;

        reader cmd.ExecuteReader();

        return reader;

 

    }catch(System.Exception exp){

        Debug.Log(exp);

        return null;

    }

}


++5.6、经过表名查询全部数据

//经过表名查询全部数据

public SqliteDataReader SelectFullFromDataBase(string tableName){

    OpenDataBase();

 

    try{

        string sql =  select * from + tableName;

        cmd.CommandText sql;

        reader cmd.ExecuteReader();

        return reader;

 

    }catch(System.Exception exp){

        Debug.Log(exp);

       return null;

    }

}


#6、 不一样平台选择不一样的存储路径

++6.1、平台-路径(数据库存储路径)

---编辑器

---PC/iOS

---Android

 

++++编辑器:

--本地路径:

  ---存储路径: Application.dataPath

  ---语法:connectionStr = “Data Source=” + Application.dataPath + “/” + databaseName;

--流路径:

  ---存储路径: Application.streamingAssetsPath

  ---语法: connectionStr = “Data Source=” + Application.streamingAssetsPath + “/” + databaseName;

--沙盒路径:

  ---存储路径: Application.persistentDataPath

  ---语法: connectionStr = “Data Source=” + Application.persistentDataPath + “/” + databaseName;

 

++++PC/iOS

--流路径:

  ---存储路径: Application.streamingAssetsPath

  ---语法: connectionStr = “Data Source” + Application.streamingAssetsPath + “/” + databaseName;

--沙盒路径:

  ---存储路径: Application.persistentDataPath

  ---语法: connectionStr = “Data Source=” + Application.persistentDataPath + “/” + databaseName;

 

++++Android

--沙盒路径:

  ---存储路径: Application.persistentDataPath

  ---语法: connectionStr = “URl=file:” + Application.persistentDataPath + “/” + databaseName;

 


++6.2Application.dataPath

++++在直接使用Application.dataPath来读取文件进行操做,移动端是没有访问权限的。


++6.3Application.streamingAssetsPath

++++直接使用Application.streamingAssetsPath来读取文件进行操做,此方法在pc/Mac电脑中可实现对文件实施“增删查改”等操做,但在移动端只支持读取操做。


++6.4Application.persistentDataPath

++++使用Application.persistentDataPath来操做文件,该文件存在手机沙盒中,由于不能直接存放文件。

  --1、经过服务器直接下载保存到该位置,也能够经过Md5码对比下载更新新的资源。

  --2、没有服务器的,只有间接经过文件流的方式从本地读取并写入Application.persistentDataPath文件下,而后再经过Application.persistentDataPath来读取操做。

++++注:在Pc/Mac电脑以及AndroidIpadiphone均可对文件进行任意操做,另外在IOS上该目录下的东西能够被iCloud自动备份。



#7、 应用程序发布到PC和移动平台

++7.1、发布到PC

++++1Mac端数据库文件会封装到MacApp中。

++++2Windows端数据库文件会放到伴随文件夹Project_Name_Data


 

++7.2、发布到Android

++++发布到Android端须要添加libsqlite3.so文件,和相应的Mono.Data.Sqlite.dllsqlite3.dllSystem.Data.dll类库。

++++注意: 全部文件放到Plugins文件夹下,libsqlite3.so放在Android文件夹下。

 

++++Android发布的特殊性在于链接本地Sqlite数据库的时候,若是没有找到数据库文件,没法建立空的数据库。鉴于此,解决方案有两种:

--1、加载libsqlite.so以后,Android会恢复自动建立数据库功能。在编写代码时,能够经过判断是否有数据库文件来判断是否存在数据库文件,从而经过从新建表从新插入数据实现。但这种方案对于数据库内容较多的项目来讲,增添了太多代码量,因此通常不使用这种方案。除非是表格内容较少时。

--2、一样须要上述的三个类库和libsqlite.so文件,但不须要从新建表和从新插入数据内容。当Android端安装应用程序时,须要一个“.apk”的安装文件,此文件内保存着咱们从Unity开发平台导入的*.sqlite文件,因此咱们能够经过www来下载该sqlite文件,从而经过IO流写入到Android本地的persistentDataPath沙盒路径。该文件保存着全部表格和数据,无需再次建立和插入,一般使用的都是这种方式,较为便捷。


++7.3Android端链接本地数据库

++++准备: 把本地数据库放在Plugins->Android->assets中。

 

 

++++Android端链接本地数据库

#if UNITY_EDITOR  //若是运行在编辑器中

string dbPath Application.dataPath+ /Plugins/Android/assets/ +User.sqlite; //经过路径找到本地数据库

DataBase db new DataBase(data source= +dbPath); //获取DataBase对象

 

#elif UNITY_ANDROID  //若是运行在Android设备中

string dbPath Application.persistentDataPath+/User.sqlite;  //将本地数据库拷贝至Android可找到的地方

 

//若是已知路径没有地方放数据库,那么咱们从Unity中拷贝

if(!File.Exists(dbPath)){

    WWW dbBytes new WWW(jar:file:// +Application.dataPath+ !/assets/ +User.sqlite);  //www先从Unity中下载到数据库

    File.WriteAllBytes(dbPathdbBytes.bytes); //拷贝至规定的地方

    DataBase db new DataBase(url=file: +dbPath);

}

#endif

 

++++注意:

--二进制文件须要放在 Plugins->Android->assets中,而后根据下面的路径就能够在Android中读取。

--string Path = “jar:file://” + Application.dataPath + “!/assets/” + “xxxx您的文件”;



#立钻哥哥Unity 学习空间: http://blog.csdn.net/VRunSoftYanlz/

++立钻哥哥推荐的拓展学习连接(Link_Url

++++立钻哥哥Unity 学习空间: http://blog.csdn.net/VRunSoftYanlz/

++++Unity引擎基础http://www.noobyard.com/article/p-ggcuedyq-ka.html

++++Unity面向组件开发http://www.noobyard.com/article/p-eiunlkzw-dt.html

++++Unity物理系统http://www.noobyard.com/article/p-mcqnwufb-kd.html

++++Unity2D平台开发http://www.noobyard.com/article/p-brjbvtac-hs.html

++++UGUI基础http://www.noobyard.com/article/p-nvzrvath-mc.html

++++UGUI进阶http://www.noobyard.com/article/p-tpspjolu-gt.html

++++UGUI综合http://www.noobyard.com/article/p-nfgrebqx-gg.html

++++Unity动画系统基础http://www.noobyard.com/article/p-otjpnbzz-dq.html

++++Unity动画系统进阶http://www.noobyard.com/article/p-hxghrtgb-bp.html

++++Navigation导航系统http://www.noobyard.com/article/p-skpvrobt-t.html

++++Unity特效渲染http://www.noobyard.com/article/p-sudpqrhk-bp.html

++++Unity数据存储http://www.noobyard.com/article/p-ybvcceul-m.html

++++Unity中Sqlite数据库http://www.noobyard.com/article/p-vxpuqxev-ca.html

++++WWW类和协程http://www.noobyard.com/article/p-alggjlwu-cy.html

++++Unity网络http://www.noobyard.com/article/p-bjvfgzwg-dw.html

++++C#事件http://www.noobyard.com/article/p-dietpjzv-gm.html

++++C#委托http://www.noobyard.com/article/p-oiohmxtc-gh.html

++++C#集合http://www.noobyard.com/article/p-vdfpislb-ex.html

++++C#泛型http://www.noobyard.com/article/p-vujvnprk-ee.html

++++C#接口http://www.noobyard.com/article/p-emexlwmu-dm.html

++++C#静态类https://blog.csdn.net/vrunsoftyanlz/article/details/78630979

++++C#中System.String类http://www.noobyard.com/article/p-uchiaxzw-cq.html

++++C#数据类型http://www.noobyard.com/article/p-kqtbvoyq-ba.html

++++Unity3D默认的快捷键http://www.noobyard.com/article/p-gbllyjbs-s.html

++++游戏相关缩写http://www.noobyard.com/article/p-pzpxsztf-gm.html

++++设计模式简单整理http://www.noobyard.com/article/p-scmbzocc-hg.html

++++U3D小项目参考https://blog.csdn.net/vrunsoftyanlz/article/details/80141811

++++UML类图http://www.noobyard.com/article/p-aakurcwi-bm.html

++++Unity知识点0001http://www.noobyard.com/article/p-bqmetnys-ep.html

++++U3D_Shader编程(第一篇:快速入门篇)http://www.noobyard.com/article/p-ptwlpwbc-gz.html

++++U3D_Shader编程(第二篇:基础夯实篇)http://www.noobyard.com/article/p-dadqpvvp-hv.html

++++立钻哥哥Unity 学习空间: http://blog.csdn.net/VRunSoftYanlz/


--_--VRunSoft : lovezuanzuan--_--