老外的一个用的SQLite的例子,看起来比较初级

代码
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Collections.Generic;
using System.Collections;


namespace ToDoDeskList
{
    
// singleton, possibly thread-safe
    public sealed class Database : IDatabase
    {
        
private static readonly IDatabase instance = new Database();

        
private SQLiteConnection handle;
        
private string databaseFile = "tasks.db";
        
private string databasePath = "";
        
private string connString;

        
public enum SelectTypes 
        {
            LEAF,
            LIST,
            SORT_CHECK,
            SORT_ALL
        }

        
private Database() { }

        
public static IDatabase Instance
        {
            
get
            {
                
return instance;
            }
        }

        
public SQLiteConnection Connection
        {
            
get
            {
                
return handle;
            }
        }

        
public void connect(string file, string path)
        {
            
try
            {
                databaseFile 
= file;
                databasePath 
= path + Path.DirectorySeparatorChar + databaseFile;

                
bool createStructure = false;

                
// check if the database file exists
                if (!File.Exists(databasePath))
                {
                    createDbFile();
                    createStructure 
= true;
                }

                connString 
= "Data Source=" + databasePath + ";Version=3";

                handle 
= new SQLiteConnection(connString);
                handle.Open();

                
if (createStructure)
                    initializeDatabase();

                
int db_version = 0;

                
try
                {
                    
string sql = "SELECT version FROM db_version WHERE id = 1";

                    SQLiteDataReader data 
= fetch(sql);
                    
while (data.Read())
                    {
                        db_version 
= Convert.ToInt32(data[0]);
                    }
                }
                
catch (Exception ex)
                {
                    db_version 
= 1;
                }

                
if (db_version < FormStart.dbVersion)
                {
                    
if (db_version == 1)
                        Database.Instance.update_db_2();

                    FormStart.dbUpdated 
= true;
                }


                
if (handle.State == ConnectionState.Closed)
                    
throw new Exception("Database connection couldn't be established.");
            
            }
            
catch (Exception e)
            {
                Error(e);
            }
        }

        
public void createDbFile()
        {
            SQLiteConnection.CreateFile(databasePath);
        }

        
public void Close()
        {
            handle.Close();
        }

        
public void correctTaskOrder()
        {
            
string sql;
            
int sort = 0;
            
if (FormStart.ini.IniReadValue("General""queue").Equals("priority"))
            {
                sql 
= "SELECT id FROM tasks WHERE done = 0 ORDER BY priority DESC, updated_at";
                SQLiteDataReader data 
= fetch(sql);
                
while (data.Read())
                {
                    sort
++;
                    sql 
= "UPDATE tasks SET sort = " + sort + " WHERE id = " + Convert.ToInt32(data[0]);
                    execute(sql);
                }
            }
        }

        
public int getSort(int id)
        {
            SQLiteDataReader data 
= fetch("SELECT sort FROM tasks WHERE id = " + id);

            
int sort = 0;
            
while (data.Read())
            {
                sort 
= Convert.ToInt32(data[0]);
            }

            
return sort;
        }

        
public int getMaxSort()
        {
            SQLiteDataReader data 
= fetch("SELECT sort FROM tasks ORDER BY sort DESC LIMIT 1");

            
int sort = 0;
            
while (data.Read())
            {
                sort 
= Convert.ToInt32(data[0]);
            }

            
return sort;
        }

        
public TaskMessenger insertTask(string note, string extNote, string dt, int priority, string ut)
        {
            
int sort = getNewSort(priority, 0);
            
            
using (SQLiteTransaction mytransaction = handle.BeginTransaction())
            {
                
using (SQLiteCommand mycommand = new SQLiteCommand(handle))
                {
                    SQLiteParameter pNote 
= new SQLiteParameter("@pNote");
                    SQLiteParameter pPriority 
= new SQLiteParameter("@pPriority");
                    SQLiteParameter pExtNote 
= new SQLiteParameter("@pExtNote");
                    SQLiteParameter pDt 
= new SQLiteParameter("@pDt");
                    SQLiteParameter pUt 
= new SQLiteParameter("@pUt");
                    SQLiteParameter pSort 
= new SQLiteParameter("@pSort");

                    mycommand.CommandText 
= "INSERT INTO tasks (note, extended_note, priority, created_at, updated_at, sort) VALUES(@pNote, @pExtNote, @pPriority, @pDt, @pUt, @pSort)";

                    mycommand.Parameters.Add(pNote);
                    mycommand.Parameters[
"@pNote"].Value = note;

                    mycommand.Parameters.Add(pPriority);
                    mycommand.Parameters[
"@pPriority"].Value = priority;

                    mycommand.Parameters.Add(pExtNote);
                    mycommand.Parameters[
"@pExtNote"].Value = extNote;

                    mycommand.Parameters.Add(pDt);
                    mycommand.Parameters[
"@pDt"].Value = dt;

                    mycommand.Parameters.Add(pUt);
                    mycommand.Parameters[
"@pUt"].Value = ut;

                    mycommand.Parameters.Add(pSort);
                    mycommand.Parameters[
"@pSort"].Value = sort;

                    mycommand.ExecuteNonQuery();
                }
                mytransaction.Commit();
            }

            SQLiteDataReader data 
= fetch("SELECT last_insert_rowid() as id");

            
int id = 0;
            
while (data.Read())
            {
                id 
= Convert.ToInt32(data[0]);
                
//MessageBox.Show("D: " + data[0].GetType());
            }

            
return new TaskMessenger(id, note, extNote, dt, priority, 0, ut, sort);
        }

        
public void insertReminder(int taskId, int day, int month, int year, int hour, int min)
        {
            SQLiteDataReader data 
= fetch("SELECT id FROM reminders WHERE task_id = " + taskId);

            
int id = 0;
            
if (data.HasRows)
            {
                
while (data.Read())
                {
                    id 
= Convert.ToInt32(data[0]);
                }
            }


            
using (SQLiteTransaction mytransaction = handle.BeginTransaction())
            {
                
using (SQLiteCommand mycommand = new SQLiteCommand(handle))
                {
                    SQLiteParameter pTaskId 
= new SQLiteParameter("@pTaskId");
                    SQLiteParameter pDay 
= new SQLiteParameter("@pDay");
                    SQLiteParameter pMonth 
= new SQLiteParameter("@pMonth");
                    SQLiteParameter pYear 
= new SQLiteParameter("@pYear");
                    SQLiteParameter pHour 
= new SQLiteParameter("@pHour");
                    SQLiteParameter pMin 
= new SQLiteParameter("@pMin");

                    
if (id > 0)
                    {
                        mycommand.CommandText 
= "UPDATE reminders SET day = @pDay, month = @pMonth, year = @pYear, hour = @pHour, min = @pMin, off = 0 WHERE id = " + id;
                    }
                    
else
                    {
                        mycommand.CommandText 
= "INSERT INTO reminders (task_id, day, month, year, hour, min) VALUES (@pTaskId, @pDay, @pMonth, @pYear, @pHour, @pMin)";
                        mycommand.Parameters.Add(pTaskId);
                        mycommand.Parameters[
"@pTaskId"].Value = taskId;
                    }
                    
                    mycommand.Parameters.Add(pDay);
                    mycommand.Parameters[
"@pDay"].Value = day;

                    mycommand.Parameters.Add(pMonth);
                    mycommand.Parameters[
"@pMonth"].Value = month;

                    mycommand.Parameters.Add(pYear);
                    mycommand.Parameters[
"@pYear"].Value = year;

                    mycommand.Parameters.Add(pHour);
                    mycommand.Parameters[
"@pHour"].Value = hour;

                    mycommand.Parameters.Add(pMin);
                    mycommand.Parameters[
"@pMin"].Value = min;

                    mycommand.ExecuteNonQuery();
                }
                mytransaction.Commit();
            }


        }

        
public void deleteReminder(int taskId)
        {
            
string sql = "DELETE FROM reminders WHERE task_id = " + taskId;
            execute(sql);
        }

        
public TaskMessenger updateTask(int id, string note, string extNote, int priority, string ut, int sort, int currentPriority)
        {
            
int newsort = 0;
            
string sql;

            
if (FormStart.ini.IniReadValue("General""queue").Equals("priority"&& priority != currentPriority)
            {
                
//Console.WriteLine("SORT: " + sort);
                sql = "UPDATE tasks SET sort = sort-1 WHERE done = 0 AND sort > " + sort;
                execute(sql);
                
//ws();
                newsort = getNewSort(priority, id);
            }
            
else
            {
                newsort 
= sort;
            }
            
            
using (SQLiteTransaction mytransaction = handle.BeginTransaction())
            {
                
using (SQLiteCommand mycommand = new SQLiteCommand(handle))
                {
                    SQLiteParameter pNote 
= new SQLiteParameter("@pNote");
                    SQLiteParameter pPriority 
= new SQLiteParameter("@pPriority");
                    SQLiteParameter pExtNote 
= new SQLiteParameter("@pExtNote");
                    SQLiteParameter pUt 
= new SQLiteParameter("@pUt");
                    SQLiteParameter pSort 
= new SQLiteParameter("@pSort");

                    mycommand.CommandText 
= "UPDATE tasks SET note = @pNote, extended_note = @pExtNote, priority = @pPriority, updated_at = @pUt, sort = @pSort WHERE id = " + id;

                    mycommand.Parameters.Add(pNote);
                    mycommand.Parameters[
"@pNote"].Value = note;

                    mycommand.Parameters.Add(pPriority);
                    mycommand.Parameters[
"@pPriority"].Value = priority;

                    mycommand.Parameters.Add(pExtNote);
                    mycommand.Parameters[
"@pExtNote"].Value = extNote;

                    mycommand.Parameters.Add(pUt);
                    mycommand.Parameters[
"@pUt"].Value = ut;

                    mycommand.Parameters.Add(pSort);
                    mycommand.Parameters[
"@pSort"].Value = newsort;

                    mycommand.ExecuteNonQuery();
                }
                mytransaction.Commit();
            }

            SQLiteDataReader data 
= fetch("SELECT done FROM tasks WHERE id = " + id);

            
int done = 0;
            
while (data.Read())
            {
                done 
= Convert.ToInt32(data[0]);
            }

            
return new TaskMessenger(id, note, extNote, null, priority, done, ut, newsort, (priority != currentPriority));
        }

        
public void deleteTask(int taskId, int sort, bool done)
        {
            
string sql;

            sql 
= "DELETE FROM tasks WHERE id = " + taskId;
            execute(sql);

            
if (!done)
            {
                adjustSort(sort);
            }
        }

        
public void deleteAllTasks()
        {
            
string sql = "DELETE FROM tasks";
            execute(sql);
        }

        
public void finishTask(int taskId, int sort)
        {
            
string sql = "UPDATE tasks SET done = 1, sort = 0 WHERE id = " + taskId;
            execute(sql);

            adjustSort(sort);
        }

        
public int unfinishTask(int taskId, int priority)
        {
            
int sort = 0;
            sort 
= getNewSort(priority, taskId);
            
            
string sql = "UPDATE tasks SET done = 0, sort = " + sort + " WHERE id = " + taskId;
            execute(sql);

            
return sort;
        }

        
public List<TaskMessenger> getAllTasks()
        {
            
return retrieveTasks(Database.SelectTypes.LEAF, null);
        }

        
public List<TaskMessenger> getAllTasks_List(bool hp, bool mp, bool lp)
        {
            
string inf = "";
            
if (hp)
            {
                inf 
+= "1";
            }
            
if (mp)
            {
                
if (inf.Length > 0)
                    inf 
+= ",";
                inf 
+= "2";
            }
            
if (lp)
            {
                
if (inf.Length > 0)
                    inf 
+= ",";
                inf 
+= "3";
            }

            
string where = String.Format("priority IN ({0})", inf);
            
return retrieveTasks(Database.SelectTypes.LIST, where);
        }

        
private int getNewSort(int priority, int taskId)
        {
            
int sort;
            List
<TaskMessenger> list;
            
string where = null;

            
if (taskId > 0)
            {
                
where = "id != " + taskId;
            }

            list 
= retrieveTasks(Database.SelectTypes.SORT_ALL, where);

            
if (list.Count > 0)
            {
                sort 
= list[0].sort + 1;
            }
            
else
            {
                sort 
= 1;
            }

            
if (FormStart.ini.IniReadValue("General""queue").Equals("priority"))
            {
                
string sql;
                
// lower number in database = higher priority (high=1, medium=2, low=3)
                where = "priority < " + priority;
                list 
= retrieveTasks(Database.SelectTypes.SORT_CHECK, where);

                
if (list.Count > 0)
                {
                    sort 
= list[0].sort;
                    sql 
= "UPDATE tasks SET sort = sort+1 WHERE done = 0 AND sort >= " + sort;
                    execute(sql);
                }
            }
           
            
return sort;
        }

        
private void ws()
        {
            
string sql = "SELECT id, sort FROM tasks WHERE done = 0 ORDER BY sort";
            SQLiteDataReader data 
= fetch(sql);
            
while (data.Read())
            {
                Console.Write(data[
1+ " ");          
            }
            Console.WriteLine();
        }

        
private List<TaskMessenger> retrieveTasks(Database.SelectTypes type, string where)
        {
            
string sql = "";
            
switch (type)
            {
                
case SelectTypes.LEAF:
                    sql 
= "SELECT id, note, extended_note, created_at, priority, done, updated_at, sort FROM tasks WHERE done = 0";
                    
if (where != null)
                    {
                        sql 
+= " AND " + where;
                    }
                    sql 
+= " ORDER BY sort";
                    
break;
                
case SelectTypes.LIST:
                    sql 
= "SELECT id, note, extended_note, created_at, priority, done, updated_at, sort FROM tasks";
                    
if (where != null)
                    {
                        sql 
+= " WHERE " + where;
                    }
                    sql 
+= " ORDER BY done, id DESC";
                    
break;
                
case SelectTypes.SORT_CHECK:
                    sql 
= "SELECT id, note, extended_note, created_at, priority, done, updated_at, sort FROM tasks WHERE done = 0";
                    
if (where != null)
                    {
                        sql 
+= " AND " + where;
                    }
                    sql 
+= " ORDER BY sort";
                    
break;
                
case SelectTypes.SORT_ALL:
                    sql 
= "SELECT id, note, extended_note, created_at, priority, done, updated_at, sort FROM tasks WHERE done = 0";
                    
if (where != null)
                    {
                        sql 
+= " AND " + where;
                    }
                    sql 
+= " ORDER BY sort DESC LIMIT 1";
                    
break;
            }
            
            SQLiteDataReader data 
= fetch(sql);

            List
<TaskMessenger> savedTasks = new List<TaskMessenger>();
            TaskMessenger m 
= null;
            ArrayList a 
= new ArrayList();

            
while (data.Read())
            {
                m 
= new TaskMessenger(Convert.ToInt32(data[0]), Convert.ToString(data[1]), Convert.ToString(data[2]), Convert.ToString(data[3]), Convert.ToInt32(data[4]), Convert.ToInt32(data[5]), Convert.ToString(data[6]), Convert.ToInt32(data[7]));
                
if (type == Database.SelectTypes.LEAF || type == Database.SelectTypes.LIST)
                {
                    a 
= retrieveReminder(m.id);
                    
if (a.Count == 6)
                    {
                        m.setReminder(Convert.ToInt32(a[
0]), Convert.ToInt32(a[1]), Convert.ToInt32(a[2]), Convert.ToInt32(a[3]), Convert.ToInt32(a[4]), Convert.ToBoolean(a[5]));
                    }
                }
                savedTasks.Add(m);
            }

            
return savedTasks;
        }

        
private ArrayList retrieveReminder(int taskId)
        {
            ArrayList a 
= new ArrayList();

            
string sql = "SELECT day, month, year, hour, min, off FROM reminders WHERE task_id = " + taskId + " AND off = 0 ORDER BY id DESC LIMIT 1";
            SQLiteDataReader data 
= fetch(sql);

            
while (data.Read())
            {
                a.Add(data[
0]);
                a.Add(data[
1]);
                a.Add(data[
2]);
                a.Add(data[
3]);
                a.Add(data[
4]);
                a.Add(data[
5]);
            }

            
return a;
        }

        
private SQLiteDataReader fetch(string sql)
        {
            
if (handle.State == ConnectionState.Closed)
                
throw new Exception("Database connection is closed.");

            SQLiteCommand cmd 
= new SQLiteCommand(sql, handle);
            SQLiteDataReader sdr 
= cmd.ExecuteReader();

            
return sdr;
        }

        
private void initializeDatabase()
        {
            
if (handle.State == ConnectionState.Closed)
                
throw new Exception("Database connection is closed.");

            
string[] tables = new string[3];
            
            
// 1.0.0-1.0.1
            
//tables[0] = "CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, extended_note TEXT, created_at TEXT);";
            
            
// 1.2.0
            tables[0= "CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, extended_note TEXT, priority INTEGER NOT NULL DEFAULT '2', done INTEGER NOT NULL DEFAULT '0', sort INTEGER NOT NULL DEFAULT '0', created_at TEXT, updated_at TEXT);";
            tables[
1= "CREATE TABLE reminders (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, off INTEGER NOT NULL DEFAULT '0', day INTEGER, month INTEGER, year INTEGER, hour INTEGER, min INTEGER);";
            tables[
2= "CREATE TABLE db_version (id INTEGER PRIMARY KEY AUTOINCREMENT, version INTEGER);";

            
foreach (string table in tables)
            {
                execute(table);
            }

            
string sql = "INSERT INTO db_version VALUES(1, 2);";
            execute(sql);

            FormStart.dbUpdated 
= true;
        }

        
private void execute(string sql)
        {
            
if (handle.State == ConnectionState.Closed)
                
throw new Exception("Database connection is closed.");

            
using (SQLiteCommand com = new SQLiteCommand())
            {
                com.CommandText 
= sql;
                com.Connection 
= handle;
                com.ExecuteNonQuery();
            }
        }

        
private void adjustSort(int sort)
        {
            
string sql = "UPDATE tasks SET sort = sort-1 WHERE sort > " + sort;
            execute(sql);
        }

        
private void Error(Exception e)
        {
            MessageBox.Show(e.ToString());
        }


        
        
//##########################################################################
        public void update_db_2()
        {
            
try
            {
                
if (!File.Exists(databasePath + ".bck"))
                {
                    File.Copy(databasePath, databasePath 
+ ".bck");
                }

                
string sql;

                sql 
= "ALTER TABLE tasks ADD priority INTEGER NOT NULL DEFAULT '2'";
                execute(sql);

                sql 
= "ALTER TABLE tasks ADD done INTEGER NOT NULL DEFAULT '0'";
                execute(sql);

                sql 
= "ALTER TABLE tasks ADD sort INTEGER NOT NULL DEFAULT '0'";
                execute(sql);

                sql 
= "ALTER TABLE tasks ADD updated_at TEXT";
                execute(sql);

                sql 
= "UPDATE tasks SET updated_at = created_at";
                execute(sql);

                sql 
= "CREATE TABLE reminders (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, off INTEGER NOT NULL DEFAULT '0', day INTEGER, month INTEGER, year INTEGER, hour INTEGER, min INTEGER);";
                execute(sql);

                sql 
= "CREATE TABLE db_version (id INTEGER PRIMARY KEY AUTOINCREMENT, version INTEGER);";
                execute(sql);
                sql 
= "INSERT INTO db_version VALUES(1, 2);";
                execute(sql);


                List
<TaskMessenger> tasks = getAllTasks();

                
using (SQLiteTransaction trans = handle.BeginTransaction())
                {
                    
using (SQLiteCommand cmd = new SQLiteCommand(handle))
                    {
                        SQLiteParameter sort 
= new SQLiteParameter();
                        SQLiteParameter id 
= new SQLiteParameter();
                        
int n = 0;

                        cmd.CommandText 
= "UPDATE tasks SET sort = ? WHERE id = ?";
                        cmd.Parameters.Add(sort);
                        cmd.Parameters.Add(id);

                        
foreach (TaskMessenger task in tasks)
                        {
                            sort.Value 
= ++n;
                            id.Value 
= task.id;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    trans.Commit();
                }
            }
            
catch (Exception exp)
            {
                
//MessageBox.Show("Updating your application to a new version may not have been successful." + Environment.NewLine + Environment.NewLine + "Error: " + Environment.NewLine + exp.Message);
                Connection.Close();
                
                
if (File.Exists(databasePath + ".bck"))
                {
                    File.Delete(databasePath 
+ ".bck");
                }

                
if (File.Exists(databasePath))
                {
                    File.Delete(databasePath);
                }

                createDbFile();

                connString 
= "Data Source=" + databasePath + ";Version=3";
                handle 
= new SQLiteConnection(connString);
                handle.Open();

                initializeDatabase();
            }

            FormStart.dbUpdated 
= true;
        }
    }
}

 

posted @ 2011-01-18 20:18  ccczqh  阅读(999)  评论(0编辑  收藏  举报