// 写得不好,放在这里只是保存代码和自用
// 在Unity中使用时,需要先在Plugins文件夹中准备好相应的文件
using System;
using System.IO;
using Mono.Data.Sqlite;
public static class SQLiteHelper
{
// 在Connect和CreateDB用到的路径字符串中,一律使用“\”而不是“/”
public static bool Connect(out SqliteConnection connection, out SqliteCommand command, string pathAndFileName, bool allowCreate = false)
{
if (!allowCreate && !File.Exists(pathAndFileName))
{ connection = null; command = null; return false; }
connection = new SqliteConnection();
connection.ConnectionString = "data source = " + pathAndFileName;
command = new SqliteCommand();
command.Connection = connection;
try
{ connection.Open(); return true; }
catch (Exception)
{ DisconnectAndClear(ref connection, ref command); return false; }
}
public static void DisconnectAndClear(ref SqliteConnection connection, ref SqliteCommand command)
{
if (command != null)
{ command.Cancel(); command.Dispose(); }
if (connection != null)
{ connection.Dispose(); }
command = null; connection = null;
}
public static SqliteDataReader ExecuteQuery(SqliteCommand command, string queryString)
{
command.CommandText = queryString;
return command.ExecuteReader();
}
public static bool CreateDB(string path, string fileName)
{
if (!Directory.Exists(path))
return false;
if (File.Exists(path + "\\" + fileName))
return false;
// ---------------- ---------------- ----------------
SqliteConnection connection;
SqliteCommand command;
if (Connect(out connection, out command, path + "\\" + fileName, true))
{
DisconnectAndClear(ref connection, ref command);
return true;
}
else
return false;
}
}