Unity3D中操作Sqlite创建本地数据库、实现增删改查

参考:[ http://blog.csdn.net/qinyuanpei/article/details/46812655]
(git地址在末尾)
开发过程中,有时需要存储一些用户相关的信息到本地,XML、Json、SQL是常用的手段,json、xml可以用于存储一些量比较小的数据,程序访问也比较方便。但是涉及到数据的增删改查,使用数据库是比较好的方式。这里简单的介绍一下Unity3D中创建数据表的方法。主要实现Unity中使用C#操作Sqlite实现数据的插入、查询、删除。用到的表如下图所示:

IDNameScoreTime
1sunme3020
2super6030
3码码小虫10033
3码码虫8015
3码码小2010
3小虫4044

一、创建数据库,建表。
二、向表中插入数据。
三、查询表中的数据。

既然要操作数据库,就需要用到C#的一些数据相关的库文件,在Unity的Assets文件夹下创建一个Plugins文件夹,放入三个库文件,Mono.Data.Sqlite.dll和System.Data.dllSqlite3.dll(可在对应的官网下载),在文末的工程文件的Plugins文件夹中有。引入对应的库文件之后,就可以操作Sqlite相关的类了。
创建一个数据库:(数据库存放在StreamingAssets文件夹下)

public class SQLManager : MonoBehaviour
{
    /// <summary>
    /// 数据库连接对象
    /// </summary>
    private SqliteConnection connection;
    /// <summary>
    /// 数据库命令
    /// </summary>
    private SqliteCommand command;
    /// <summary>
    /// 数据读取定义
    /// </summary>
    private SqliteDataReader reader;
    /// <summary>
    /// 本地数据库名字
    /// </summary>
    public string sqlName;
    public void Start()
    {
        this.CreateSQL();
        this.OpenSQLaAndConnect();
    }
    //创建数据库文件
    public void CreateSQL()
    {
        if (!File.Exists(Application.streamingAssetsPath + "/" + this.sqlName))
        {
            this.connection = new SqliteConnection("data source=" + Application.streamingAssetsPath + "/" + this.sqlName);
            this.connection.Open();
            this.CreateSQLTable(
                "用户",
                "CREATE TABLE 用户(" +
                "ID             INT ," +
                "Name           TEXT," +
                "Age            INT ," +
                "Score          INT," +
                "Time           INT)",
                null,
                null
            );
            this.connection.Close();
            return;
        }

    }
    //打开数据库
    public void OpenSQLaAndConnect()
    {
        this.connection = new SqliteConnection("data source=" + Application.streamingAssetsPath + "/" + this.sqlName);
        this.connection.Open();        
    }
    /// <summary>
    ///执行SQL命令,并返回一个SqliteDataReader对象
    /// <param name="queryString"></param>
    public SqliteDataReader ExecuteSQLCommand(string queryString)
    {
        this.command = this.connection.CreateCommand();
        this.command.CommandText = queryString;
        this.reader = this.command.ExecuteReader();
        return this.reader;
    }
    /// <summary>
    /// 通过调用SQL语句,在数据库中创建一个表,顶定义表中的行的名字和对应的数据类型
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="columnNames"></param>
    /// <param name="dataTypes"></param>
    public SqliteDataReader CreateSQLTable(string tableName, string commandStr=null, string[] columnNames = null, string[] dataTypes = null)
    {
        //string queryString = "CREATE TABLE " + tableName + "( " + columnNames[0] + " " + dataTypes[0];
        //for (int i = 1; i < columnNames.Length; i++)
        //{
        //    queryString += ", " + columnNames[i] + " " + dataTypes[i];
        //}
        //queryString += "  ) ";
        //  return ExecuteSQLCommand(queryString);

        return ExecuteSQLCommand(commandStr);
    }
    /// <summary>
    /// 关闭数据库连接,注意这一步非常重要,最好每次测试结束的时候都调用关闭数据库连接
    /// 如果不执行这一步,多次调用之后,会报错,数据库被锁定,每次打开都非常缓慢
    /// </summary>
    public void CloseSQLConnection()
    {
        if (this.command != null)
        {
            this.command.Cancel();
        }

        if (this.reader != null)
        {
            this.reader.Close();
        }

        if (this.connection != null)
        {
            this.connection.Close();

        }
        this.command = null;
        this.reader = null;
        this.connection = null;
        Debug.Log("已经断开数据库连接");
    }
    //当退出应用程序的时候关闭数据库连接
    private void OnApplicationQuit()
    {
        //当程序退出时关闭数据库连接,不然会重复打开数据卡,造成卡顿
        this.CloseSQLConnection();
        Debug.Log("程序退出");
    }

数据库的创建、连接、关闭已经完成了,接下来,实现向数据表中插入数据,具体代码如下。

 /// <summary>
    /// 向数据库中插入数据
    /// </summary>
    SqliteDataReader InsertDataToSQL(string tableName,string[] insertValues)
    {
        string commandString= "INSERT INTO " + tableName + " VALUES (" + insertValues[0];
        for (int i = 1; i < insertValues.Length; i++)
        {
            commandString += "," + insertValues[i];
        }
        commandString += ")";
        return ExecuteSQLCommand(commandString);

这里为了临时做测试,我想数据库中添加一些数据

 /// <summary>
    /// 调用数据插入函数,向数据库中插入5条数据
    /// </summary>
    void TempInsertData()
    {

        for (int i = 0; i <5; i++)
        {
            InsertDataToSQL(
                "用户",
                new[]
                    {
                        i.ToString(),"'"+"码码小虫"+IDCount.ToString()+"'", (i * 6).ToString(), (i * 50).ToString(),
                        (i*5).ToString()
                    });
            IDCount++;
        }

有些时候需要对整张数据表操作,比如读取数据表中的==所有行的行数==:

int GetRowCount()
    {
        this.command = this.connection.CreateCommand();
        this.command.CommandText = "select * from 用户";
        this.reader = this.command.ExecuteReader();     

        DataTable table=new DataTable();

        table.Load(this.reader);
        Debug.Log(table.Rows.Count);

        return table.Rows.Count;
    }

对数据表中的数据进行删选,返回满足条件的数据

 public SqliteDataReader ReadTable(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
    {
        string queryString = "SELECT " + items[0];
        for (int i = 1; i < items.Length; i++)
        {
            queryString += ", " + items[i];
        }
        queryString += " FROM " + tableName + " WHERE " + colNames[0] + " " + operations[0] + " " + colValues[0];
        for (int i = 0; i < colNames.Length; i++)
        {
            queryString += " AND " + colNames[i] + " " + operations[i] + " " + colValues[0] + " ";
        }
        return this.ExecuteSQLCommand(queryString);
    }

调用方式如下所示,放在触发函数

            var tempCount = 0;

            ReadTable("用户", new[] { "Age", "Time","Name" }, new[] { "Score" }, new[] { ">=" }, new[] { "10" });
            while (this.reader.Read())
            {
                tempCount++;
                Debug.Log(reader.GetString(reader.GetOrdinal("Name")));
               // Debug.Log(reader.GetInt32(reader.GetOrdinal("Time")));
               // Debug.Log(tempCount);
            }

到这里,基本的一些操作就差不多了,以上内容纯属搬砖,参考文章链接:
http://blog.csdn.net/qinyuanpei/article/details/46812655
Git地址:
扫码获取文章地址(文末有工程地址):


这里写图片

好的,我可以为您提供一个简单的SQLite数据库创建增删改查操作的示例。以下是步骤: 1. 创建一个继承自SQLiteOpenHelper的类,该类用于创建和管理数据库。在该类的构造函数,您需要传入数据库名称、版本号等参数,并在onCreate()方法创建数据库表结构。 ```java public class DBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "my_db"; private static final int DB_VERSION = 1; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表结构 String sql = "CREATE TABLE user(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库升级操作 } } ``` 2. 在需要使用数据库的Activity或Fragment创建DBHelper实例,并调用getWritableDatabase()方法获取可写数据库对象。 ```java DBHelper dbHelper = new DBHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); ``` 3. 插入数据。您可以使用ContentValues对象封装要插入的数据,然后调用insert()方法进行插入操作。 ```java ContentValues values = new ContentValues(); values.put("name", "Tom"); values.put("age", 20); db.insert("user", null, values); ``` 4. 查询数据。您可以使用query()方法进行查询操作,并将结果封装成Cursor对象。 ```java Cursor cursor = db.query("user", null, null, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); // do something with the data } cursor.close(); ``` 5. 更新数据。您可以使用ContentValues对象封装要更新的数据,并调用update()方法进行更新操作。 ```java ContentValues values = new ContentValues(); values.put("age", 21); db.update("user", values, "name=?", new String[]{"Tom"}); ``` 6. 删除数据。您可以使用delete()方法进行删除操作。 ```java db.delete("user", "age>?", new String[]{"18"}); ``` 以上是SQLite数据库创建增删改查操作的一个简单示例,当然,在您的实际开发过程,您需要根据实际需求进行更加详细的设计和开发。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值