[计算机] Unity—Mono.Data.Sqlite

查看:411 |回复:1 | 2022-8-29 13:46:53

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 MrTang1988 于 2022-8-29 19:13 编辑

一、常用属性
Depth:获取一个值,用于指示当前行的嵌套深度
FieldCount:获取当前行中的列数
HasRows:获取一个值,该值指示SQLDataReader是否有行
IsClosed:指定的SQLDataReader实例是否已关闭
Item[Int32]:获取指定列(数字索引),通常在While.Read()中使用
Item[String]:获取指定列(字符串索引),通常在While.Read()中使用
RecordsAffected:获取执行SqlDataReader中未隐藏的字段数目
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             string str = "server=.;database=JunTest;uid=sa;pwd=123;Asynchronous Processing=true";
  6.             SqlConnection conn = new SqlConnection(str);    //创建连接
  7.             SqlCommand cmd = conn.CreateCommand();          //创建SqlCommand对象
  8.             cmd.CommandText = "SELECT * FROM Person";
  9.             conn.Open();                            //打开连接

  10.             using (SqlDataReader reader = cmd.ExecuteReader())
  11.             {
  12.                 Console.WriteLine(reader.FieldCount);   //2  获取列数
  13.                 Console.WriteLine(reader.Depth);        //0  嵌套深度
  14.                 Console.WriteLine(reader.HasRows);      //true  是否包含行
  15.                 Console.WriteLine(reader.IsClosed);     //false SqlDataReader是否关闭
  16.                 Console.WriteLine(reader.RecordsAffected);      //-1 执行T-SQL语句所插入、修改、删除的行数
  17.                 Console.WriteLine(reader.VisibleFieldCount);    //2  未隐藏的字段数目(一共就两列)

  18.                 while (reader.Read())
  19.                 {
  20.                     Console.WriteLine(reader["PersonName"]);
  21.                   //Console.WriteLine(reader[1]);   通过数字索引或字符串索引访问
  22.                 }
  23.             }

  24.             conn.Close();                           //关闭连接
  25.             Console.ReadKey();
  26.         }
  27.     }
点击此处复制文本

二、常用方法
Read:前进到下一记录,异步版本ReadAsync
GetString:返回指定类型的值,其他的类型
NextResult:当处理批批处理T-SQL语句时,跳到下一结果 异步版本NextResultAsync
GetValue:获取该列的值,返回object类型
GetValues:使用当前列,来填充参数中的对象数组
Close:关闭SqlDataReader对象

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             string str = "server=.;database=JunTest;uid=sa;pwd=123;Asynchronous Processing=true";
  6.             SqlConnection conn = new SqlConnection(str);    //创建连接
  7.             SqlCommand cmd = conn.CreateCommand();          //创建SqlCommand对象
  8.             cmd.CommandText = "SELECT * FROM Person";
  9.             conn.Open();                            //打开连接

  10.             using (SqlDataReader reader = cmd.ExecuteReader())
  11.             {
  12.                 while (reader.Read())
  13.                 {
  14.                     Console.WriteLine(reader.IsDBNull(1));      //是否是null值
  15.                     Console.WriteLine(reader.GetString(1));     //Get什么类型就返回什么类型,这没啥好说的。
  16.                 }
  17.                 Console.WriteLine(reader.GetName(1));               //PersonName 由数字获得列名
  18.                 Console.WriteLine(reader.GetOrdinal("PersonName")); //1 由列名获取其在reader中的数字索引

  19.                 if (reader.NextResult())
  20.                 {
  21.                     Console.WriteLine(reader.GetString(1));
  22.                 }
  23.             }
  24.             conn.Close();                           //关闭连接
  25.             Console.ReadKey();
  26.         }
  27.     }
点击此处复制文本


Demo:
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using Mono.Data.Sqlite;
  5. /// <summary>
  6. /// SQLite数据库操作类
  7. /// </summary>
  8. public class SqliteAccess
  9. {
  10.         private SqliteConnection conn; // SQLite连接
  11.         private SqliteCommand cmd; // SQLite命令
  12.         private SqliteDataReader reader;
  13.         public SqliteAccess(string connectionString)
  14.         {
  15.                 OpenDB(connectionString);
  16.         }
  17.         public SqliteAccess() { }
  18.         /// <summary>
  19.         /// 打开数据库
  20.         /// </summary>
  21.         /// <param name="connectionString"></param>
  22.         public void OpenDB(string connectionString)
  23.         {
  24.                 try
  25.                 {
  26.                         conn = new SqliteConnection(connectionString);
  27.                         conn.Open();
  28.                         Debug.Log("Connected to db,连接数据库成功!");
  29.                 }
  30.                 catch (Exception e)
  31.                 {
  32.                         string temp1 = e.ToString();
  33.                         Debug.Log(temp1);
  34.                 }
  35.         }
  36.         /// <summary>
  37.         /// 关闭数据库连接
  38.         /// </summary>
  39.         public void CloseSqlConnection()
  40.         {
  41.                 if (cmd != null) { cmd.Dispose(); cmd = null; }
  42.                 if (reader != null) { reader.Dispose(); reader = null; }
  43.                 if (conn != null) { conn.Close(); conn = null; }
  44.                 Debug.Log("Disconnected from db.关闭数据库!");
  45.         }
  46.         /// <summary>
  47.         /// 执行SQL语句
  48.         /// </summary>
  49.         /// <param name="sqlQuery"></param>
  50.         /// <returns></returns>
  51.         public SqliteDataReader ExecuteQuery(string sqlQuery)
  52.         {
  53.                 cmd = conn.CreateCommand();
  54.                 cmd.CommandText = sqlQuery;
  55.                 reader = cmd.ExecuteReader();
  56.                 return reader;
  57.         }

  58.         /// <summary>
  59.         /// 查询表中全部数据 param tableName=表名
  60.         /// </summary>
  61.         public SqliteDataReader ReadFullTable(string tableName)
  62.         {
  63.                 string query = "SELECT * FROM " + tableName;
  64.                 return ExecuteQuery(query);
  65.         }
  66.         /// <summary>
  67.         /// 插入数据 param tableName=表名 values=插入数据内容
  68.         /// </summary>
  69.         public SqliteDataReader InsertInto(string tableName, string[] values)
  70.         {
  71.                 string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
  72.                 for (int i = 1; i < values.Length; ++i)
  73.                 {
  74.                         query += ", " + values[i];
  75.                 }
  76.                 query += ")";
  77.                 return ExecuteQuery(query);
  78.         }
  79.         /// <summary>
  80.         /// 更新数据 param tableName=表名 cols=更新字段 colsvalues=更新内容 selectkey=查找字段(主键) selectvalue=查找内容
  81.         /// </summary>
  82.         public SqliteDataReader UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue)
  83.         {
  84.                 string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0];
  85.                 for (int i = 1; i < colsvalues.Length; ++i)
  86.                 {
  87.                         query += ", " + cols[i] + " =" + colsvalues[i];
  88.                 }
  89.                 query += " WHERE " + selectkey + " = " + selectvalue + " ";
  90.                 return ExecuteQuery(query);
  91.         }

  92.         /// <summary>
  93.         /// 删除数据 param tableName=表名 cols=字段 colsvalues=内容
  94.         /// </summary>
  95.         public SqliteDataReader Delete(string tableName, string[] cols, string[] colsvalues)
  96.         {
  97.                 string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];
  98.                 for (int i = 1; i < colsvalues.Length; ++i)
  99.                 {
  100.                         query += " or " + cols[i] + " = " + colsvalues[i];
  101.                 }
  102.                 return ExecuteQuery(query);
  103.         }
  104.         /// <summary>
  105.         /// 插入数据 param tableName=表名 cols=插入字段 value=插入内容
  106.         /// </summary>
  107.         public SqliteDataReader InsertIntoSpecific(string tableName, string[] cols, string[] values)
  108.         {
  109.                 if (cols.Length != values.Length)
  110.                 {
  111.                         throw new SqliteException("columns.Length != values.Length");
  112.                 }
  113.                 string query = "INSERT INTO " + tableName + "(" + cols[0];
  114.                 for (int i = 1; i < cols.Length; ++i)
  115.                 {
  116.                         query += ", " + cols[i];
  117.                 }
  118.                 query += ") VALUES (" + values[0];
  119.                 for (int i = 1; i < values.Length; ++i)
  120.                 {
  121.                         query += ", " + values[i];
  122.                 }
  123.                 query += ")";
  124.                 return ExecuteQuery(query);
  125.         }
  126.         /// <summary>
  127.         /// 删除表中全部数据
  128.         /// </summary>
  129.         public SqliteDataReader DeleteContents(string tableName)
  130.         {
  131.                 string query = "DELETE FROM " + tableName;
  132.                 return ExecuteQuery(query);
  133.         }
  134.         /// <summary>
  135.         /// 创建表 param name=表名 col=字段名 colType=字段类型
  136.         /// </summary>
  137.         public SqliteDataReader CreateTable(string name, string[] col, string[] colType)
  138.         {
  139.                 if (col.Length != colType.Length)
  140.                 {
  141.                         throw new SqliteException("columns.Length != colType.Length");
  142.                 }
  143.                 string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
  144.                 for (int i = 1; i < col.Length; ++i)
  145.                 {
  146.                         query += ", " + col[i] + " " + colType[i];
  147.                 }
  148.                 query += ")";
  149.                 return ExecuteQuery(query);
  150.         }
  151.         /// <summary>
  152.         /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容
  153.         /// </summary>
  154.         public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
  155.         {
  156.                 if (col.Length != operation.Length || operation.Length != values.Length)
  157.                 {
  158.                         throw new SqliteException("col.Length != operation.Length != values.Length");
  159.                 }
  160.                 string query = "SELECT " + items[0];
  161.                 for (int i = 1; i < items.Length; ++i)
  162.                 {
  163.                         query += ", " + items[i];
  164.                 }
  165.                 query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
  166.                 for (int i = 1; i < col.Length; ++i)
  167.                 {
  168.                         query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";
  169.                 }
  170.                 return ExecuteQuery(query);
  171.         }
  172.         /// <summary>
  173.         /// 查询表
  174.         /// </summary>
  175.         public SqliteDataReader Select(string tableName, string col, string values)
  176.         {
  177.                 string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + values;
  178.                 return ExecuteQuery(query);
  179.         }
  180.         public SqliteDataReader Select(string tableName, string col, string operation, string values)
  181.         {
  182.                 string query = "SELECT * FROM " + tableName + " WHERE " + col + operation + values;
  183.                 return ExecuteQuery(query);
  184.         }
  185.         /// <summary>
  186.         /// 升序查询
  187.         /// </summary>
  188.         public SqliteDataReader SelectOrderASC(string tableName, string col)
  189.         {
  190.                 string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " ASC";
  191.                 return ExecuteQuery(query);
  192.         }
  193.         /// <summary>
  194.         /// 降序查询
  195.         /// </summary>
  196.         public SqliteDataReader SelectOrderDESC(string tableName, string col)
  197.         {
  198.                 string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " DESC";
  199.                 return ExecuteQuery(query);
  200.         }
  201.         /// <summary>
  202.         /// 查询表行数
  203.         /// </summary>
  204.         public SqliteDataReader SelectCount(string tableName)
  205.         {
  206.                 string query = "SELECT COUNT(*) FROM " + tableName;
  207.                 return ExecuteQuery(query);
  208.         }
  209. }
点击此处复制文本
  1. using Mono.Data.Sqlite;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;

  5. public class User : MonoBehaviour
  6. {
  7.     private SqliteAccess db;
  8.     protected SqliteDataReader reader;
  9.     private string dbName = "sqlite.db";
  10.    
  11.     private void Start()
  12.     {
  13.         OpenDB();

  14.         reader = db.ReadFullTable("User");

  15.         for(int i = 0; i < reader.VisibleFieldCount; i++)
  16.         {
  17.             Debug.Log(reader.GetName(i)+"--"+reader.GetValue(i));
  18.         }
  19.         while (reader.Read())
  20.         {
  21.             Debug.Log(reader["username"]);
  22.             //Console.WriteLine(reader[1]);   通过数字索引或字符串索引访问
  23.         }

  24.         reader.Close();
  25.     }  
  26. }
点击此处复制文本
2022-8-29 13:46:53  
 赞 赞 1

使用道具 登录

1个回答,把该问题分享到群,邀请大神一起回答。
2#
回复 收起回复
2023-3-1 12:07:12   回复
 赞 赞 1

使用道具 登录

CG 游戏行业专业问题

手机游戏引擎手游引擎Unity3D技术
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表