Unity学习笔记——数据库Sqlite

tech2022-08-02  141

需要添加两个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(); } }
最新回复(0)