Unity学习笔记——数据库Sqlite

本文详细介绍在Unity游戏开发环境中使用SQLite数据库的操作方法,包括数据库的插入、更新、单条查询及多条查询等核心功能实现。通过具体代码示例,展示了如何在Unity中连接SQLite数据库,执行SQL语句,并读取查询结果。


需要添加两个dll文件

数据库放在上图路径下注意文件名不能错必须是这个

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
public class SQLDemo : MonoBehaviour
{
    //数据库连接对象
    private SqliteConnection con;
    //数据库指令对象
    private SqliteCommand command;
    //数据库读取对象
    private SqliteDataReader reader;
    
    //数据库地址字符串
    private string connectionString;
    // Start is called before the first frame update
    void Start()
    {
        connectionString = "Data Source = " + Application.streamingAssetsPath +"/HeroDatabase.sqlite";
        //实例化连接对象
        con = new SqliteConnection(connectionString);

        //打开连接对象
        con.Open();

        //创建指令对象
        command = con.CreateCommand();


        SqlSelectMutiple();
        
    }

    private void SqlInsert()
    {
        //设置Sql语句
        command.CommandText = "Insert Into HeroTable Values ('皮城女警',1,120,20)";

        //执行sql语句
        //方法一
        //执行sql语句并返回受影响的行数,int型
        //适用于增、删、改
        int rows = command.ExecuteNonQuery();


        Debug.Log(rows);
    }
    private void SqlUpdate()
    {
        //设置Sql语句
        command.CommandText = "Update HeroTable Set HeroLevel=2 where HeroName='皮城女警'";

        int rows = command.ExecuteNonQuery();

    }
    private void SqlSelectSingle()
    {
        //设置Sql语句
        command.CommandText = "Select HeroAD From HeroTable where HeroName='皮城女警'";
        //方法二
        //执行Sql语句,返回查询到的第一个结果(第一行第一列)
        //适用查询单个数据
        object selectresult=command.ExecuteScalar();
        Debug.Log(selectresult);
    }
    private void SqlSelectMutiple()
    {
        //设置Sql语句
        command.CommandText = "select * From HeroTable";
        //方法三
        //执行sql语句,并返回所有查询到的结果到读取器
        reader=command.ExecuteReader();

        //如何读取数据?

        //读取下一行数据,如果没有下一行返回false,否则返回true
        while (reader.Read())
        {
            Debug.Log(reader.FieldCount);   //reader.fieldCount列数

            for(int i = 0; i< reader.FieldCount; i++)
            {
               object value= reader.GetValue(i);    //读取当前行的第i列的值
               
                Debug.Log(value);
            }
        }

        reader.Close();   //关闭读取器
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    /// <summary>
    /// 当应用程序关闭时调用一次
    /// 关闭数据库连接
    /// </summary>
    private void OnApplicationQuit()
    {
        //关闭连接
        con.Close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值