SQLite

  1. SQLite

SQLite

SQLite

新建文件夹Plugins导入Mono.Data Mono.Data.Sqlite sqlite3 sqlite3等资源即可调用相关库
using Mono.Data.Sqlite;
新建文件夹streamingAssets导入创建的DataBase(文件夹名字不能错)

以下为需要定义的对象

1
2
3
4
5
6
7
8
//数据库访问路径
private string dataBasePath;
//数据库连接对象
private SqliteConnection con;
//数据库指令对象
private SqliteCommand cmd;
//数据库读取对象
private SqliteDataReader reader;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void Start()
{
//找到数据库的路径
#if UNITY_EDITOR
dataBasePath = "Data Source = " + Application.streamingAssetsPath + "/xxxDataBase(文件名).sqlite";
#endif
#if UNITY_STANDALONE_WIN
dataBasePath = "Data Source = " + Application.streamingAssetsPath + "/xxxDataBase.sqlite";
#endif
//实例化数据库连接对象,并绑定数据库路径链接
con = new SqliteConnection(dataBasePath);
//开始链接
con.Open();
//创建数据库指令对象
cmd = con.CreateCommand();
  • SQL三种执行方法
  1. cmd.CommandText = "Insert Into StudentsTable Values('xiaohong','18','TianJin')";
    int row = cmd.ExecuteNonQuery();
    Debug.Log(row);
    执行SQL,返回受影响的行数
    用于执行增删改

  2. cmd.CommandText = "Select Name From StudentsTable";
    object val = cmd.ExecuteScalar();
    Debug.Log(val);
    执行SQL语句,返回查询到的第一行第一列的数据
    用于执行查询单个数据

  3. cmd.CommandText = "Select * From StudentsTable";
    执行SQL语句,返回查询后的结果
    用于执行查询多个数据
    reader = cmd.ExecuteReader();
    读取下一行,若没有下一行,则返回null
    reader.Read();
    打印结果的列数reader.FieldCount

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
        string currentColumn = "";
    for (int i = 0; i < reader.FieldCount; i++)
    {
    currentColumn += reader.GetName(i).ToString();
    currentColumn += "\t";
    }
    Debug.Log(currentColumn);
    while (reader.Read())
    {
    currentColumn = "";
    for (int i = 0; i < reader.FieldCount; i++)
    {
    currentColumn += reader.GetValue(i).ToString();
    currentColumn += "\t";
    }
    Debug.Log(currentColumn);
    }
    if (!reader.IsClosed)
    {
    reader.Close();//read使用完一次就要关闭一次
    }
    }
    /// <summary>
    /// 程序关闭时调用一次
    /// </summary>
    private void OnApplicationQuit()
    {
    if(reader != null)
    {
    reader.Close();
    reader = null;
    }
    if(cmd != null)
    {
    cmd.Dispose();
    cmd = null;
    }
    if(con != null)
    con.Close();
    }

×

喜欢就点赞,疼爱就打赏