Development environment Unity2018.4 .net4.x
Target platform pc, android
The reference library is imported into Mono.Data.Sqlite.dll from Editor \ Data \ Mono \ lib \ mono \ 2.0 (System.Data.dll is not required)
Download sqlite.dll libsqlite3.so from the Internet or https://github.com/feigebabata/unityTools/tree/master/SqliteTool/Plugins
1. Link database statement new SqliteConnection ("data source =" + databasePath); // databasePath is the database file path common to all platforms
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. Total number of database tables: string sql = "select count (*) from sqlite_master";
3. Whether the table "Test1" exists
string sql = "select count(*) from sqlite_master where type='table' and name='Test1'";
command.CommandText = sql;
Debug.Log(command.ExecuteScalar());
4. Table creation: "create table table name (field 1 type, field 2 type)"
5. C # Sqlite type conversion can be written without conversion: "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. Drop the table "Test2": string sql = "drop table Test2";
7. Add data: "insert into table name (field 1, field 2) values (data 1, data 2)"
8. Update data: "update table name set update field 1 = update data 1 where field 2 = data 2"
9. Delete data: "delete from table name where field 1 = data 2"
10. Query data: "select * from table name where field 1 = data 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();
}