开发环境Unity2018.4 .net4.x
目标平台pc,android
引用库 从Editor\Data\Mono\lib\mono\2.0 导入 Mono.Data.Sqlite.dll (不需要System.Data.dll)
从网上下载sqlite.dll libsqlite3.so 或者https://github.com/feigebabata/unityTools/tree/master/SqliteTool/Plugins
1.链接数据库语句 new SqliteConnection("data source = "+databasePath);//databasePath是数据库文件路径 各平台通用
IEnumerator Start()
{
string databasePath = Path.Combine(Application.persistentDataPath,"main.db");
if(!File.Exists(databasePath))
{
string copyPath = Path.Combine(Application.streamingAssetsPath,"main.db");
UnityWebRequest uwr = new UnityWebRequest(copyPath);
uwr.downloadHandler = new DownloadHandlerFile(databasePath);
yield return uwr.SendWebRequest();
if(uwr.isHttpError || uwr.isNetworkError)
{
log(uwr.error);
}
}
// string databasePath = Path.Combine(Application.streamingAssetsPath,"main.db");
connection = new SqliteConnection("data source = "+databasePath);
connection.Open();
command = connection.CreateCommand();
Debug.Log(connection.Database);
// command.CommandText = "insert into Test2(Age,Name) values(66,'baba')";
// command.ExecuteReader();
// seletcAllTab();
yield return null;
}
2.数据库表总数:string sql = "select count(*) from sqlite_master";
3.表"Test1"是否存在
string sql = "select count(*) from sqlite_master where type='table' and name='Test1'";
command.CommandText = sql;
Debug.Log(command.ExecuteScalar());
4.表创建:"create table 表名(字段1 类型,字段2 类型)"
5.C# Sqlite类型转换 无需转换 这样写也可以: "create table Data2(Name String,ID Int32)"
string CS2DB(Type type)
{
string result = "Text";
if(type==typeof(Int32))
{
result = "Int";
}
else if (type == typeof(String))
{
result = "Text";
}
else if (type == typeof(Single))
{
result = "FLOAT";
}
else if (type == typeof(Boolean))
{
result = "Bool";
}
return result;
}
6.删除表"Test2": string sql = "drop table Test2";
7.添加数据:"insert into 表名(字段1,字段2) values(数据1,数据2)"
8.更新数据:"update 表名 set 更新字段1=更新数据1 where 字段2=数据2"
9.删除数据:"delete from 表名 where 字段1=数据2"
10.查询数据:"select * from 表名 where 字段1=数据1"
void Select(string _table)
{
string sql = $"select * from {_table}";
log(sql);
command.CommandText = sql;
reader = command.ExecuteReader();
StringBuilder vals_sb = new StringBuilder();
while(reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
vals_sb.AppendFormat("{0}:{1},",reader.GetName(i),reader.GetValue(i));
}
log(vals_sb.ToString());
vals_sb.Clear();
}
command.Dispose();
}