· 8 years ago · Jul 16, 2018, 03:38 PM
1using UnityEngine;
2using System.Data;
3using Mono.Data.Sqlite;
4using System.IO;
5
6public class SqliteTest : MonoBehaviour {
7
8 // Use this for initialization
9 void Start () {
10
11 // Create database
12 string connection = "URI=file:" + Application.persistentDataPath + "/" + "My_Database";
13
14 // Open connection
15 IDbConnection dbcon = new SqliteConnection(connection);
16 dbcon.Open();
17
18 // Create table
19 IDbCommand dbcmd;
20 dbcmd = dbcon.CreateCommand();
21 string q_createTable = "CREATE TABLE IF NOT EXISTS my_table (id INTEGER PRIMARY KEY, val INTEGER )";
22
23 dbcmd.CommandText = q_createTable;
24 dbcmd.ExecuteReader();
25
26 // Insert values in table
27 IDbCommand cmnd = dbcon.CreateCommand();
28 cmnd.CommandText = "INSERT INTO my_table (id, val) VALUES (0, 5)";
29 cmnd.ExecuteNonQuery();
30
31 // Read and print all values in table
32 IDbCommand cmnd_read = dbcon.CreateCommand();
33 IDataReader reader;
34 string query ="SELECT * FROM my_table";
35 cmnd_read.CommandText = query;
36 reader = cmnd_read.ExecuteReader();
37
38 int fieldCount = reader.FieldCount;
39 while (reader.Read())
40 {
41 Debug.Log("id: " + reader[0].ToString());
42 Debug.Log("val: " + reader[1].ToString());
43 }
44
45 // Close connection
46 dbcon.Close();
47
48 }
49
50 // Update is called once per frame
51 void Update () {
52
53 }
54}