1.下载Sqlite库文件libsqlite3.so、sqlite3.dll,网上找的话到处都是。
2.将已建好的数据库文件放到StreamingAssets下。
3.在Andorid上运行时,需要将数据库文件复制到另一个位置。这里需要WWW类,务必在协程中调用。
public class DbHelper : MonoSingletion<DbHelper>
{
private string connectString;
private SqliteConnection dbconn;
private SqliteCommand dbcmd;
private SqliteDataReader reader;
int roundId=0;//轮号
private void Start()
{
#if UNITY_EDITOR
connectString = "URI=file:" + Path.Combine(Application.streamingAssetsPath, "ShootRecord.db");
#elif UNITY_ANDROID
StartCoroutine(copyDbFile());
#endif
}
IEnumerator copyDbFile()
{
string dataSandBoxPath = Application.persistentDataPath + "/ShootRecord.db";
if (!Directory.Exists(Application.persistentDataPath))
{
Directory.CreateDirectory(Application.persistentDataPath);
}
WWW loadWWW = new WWW(Path.Combine(Application.streamingAssetsPath, "ShootRecord.db"));
Debug.Log(Path.Combine(Application.streamingAssetsPath, "ShootRecord.db"));
yield return loadWWW;
File.WriteAllBytes(dataSandBoxPath, loadWWW.bytes);
connectString = "URI=file:" + dataSandBoxPath;
}
private void Update()
{
if (listScorePoint.Count > 0 && (Time.time - tmLastAdd) > 3.0f)
{
ExecuteInsertScorePoint();
}
}
/// <summary>
/// 关闭连接
/// </summary>
public void CloseDB()
{
if (reader != null)
{
reader.Close();
reader = null;
}
if (dbcmd != null)
{
dbcmd.Dispose();
dbcmd = null;
}
if (dbconn != null)
{
dbconn.Close();
dbconn = null;
}
}
public void OpenDB()
{
dbconn = new SqliteConnection(connectString);
dbconn.Open();
}
public int NewRound()
{
string sql = "INSERT INTO Round(StartDateTime) VALUES(DateTime('now'));SELECT last_insert_rowid();";
OpenDB();
int row = 0;
try
{
dbcmd = dbconn.CreateCommand();
dbcmd.CommandText = sql;
reader = dbcmd.ExecuteReader();
if (reader.RecordsAffected == 1)
{
row = System.Convert.ToInt32(reader.GetValue(0));
}
}
catch (Exception ex)
{
Debug.Log("INSERT INTO Error:" + ex.Message);
}
CloseDB();
roundId = row;
return row;
}
}
public class ShootPoint
{
public float time;
public bool isShoot;
public string score;
public string x;
public string y;
public ShootPoint(float tm, bool sht, string sc, string _x, string _y)
{
time = tm;
isShoot = sht;
score = sc;
x = _x;
y = _y;
}
}