簡單SQLite 數據庫操作Demo

1 篇文章 0 订阅

public class DbHelperSQLite
    {
        public string connectionString = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + @"WIP.db;Version=3;";


        public event EventHandler<SQLiteMessageEventArg> SQLiteMessageEvent;


        public DbHelperSQLite()
        { }
   
        /// <summary>
        /// 執行單條SQL語句,返回值(bool)
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public bool ExecuteSql(string SQLString)
        {
            var eventHandle = SQLiteMessageEvent;
            string msg = "";


            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.ExecuteNonQuery();
                        msg = "SQL Command: " + SQLString + " Excute Success!";
                        if (eventHandle != null)
                        {
                            eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.Msg, msg, SQLString));
                        }
                        return true;
                    }
                    catch (SQLiteException ex)
                    {
                        msg = "Execute SQL Error Message: " + ex.Message;
                        if (eventHandle != null)
                        {
                            eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.ErrorSql, msg, SQLString));
                        }
                        return false;
                    }
                    finally
                    {
                        connection.Close();
                        cmd.Dispose();
                    }
                }
            }
        }

        /// <summary>
        /// 獲取最大值,返回值(int)
        /// </summary>
        /// <param name="FieldName">欄位名稱</param>
        /// <param name="TableName">表名稱</param>
        /// <returns></returns>
        public int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
	    return int.Parse(obj.ToString());
        }

        /// <summary>
        /// 單值查詢,返回查詢結果(Object)
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public object GetSingle(string SQLString)
        {
            var eventHandle = SQLiteMessageEvent;
            string msg = "";


            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            msg = "WARN : SQL Command Return null! [ " + SQLString + "]";
                            if (eventHandle != null)
                            {
                                eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.Msg, msg, SQLString));
                            }
                            return null;
                        }
                        else
                        {
                            msg = "SQL Command: " + SQLString + " Excute Success!";
                            if (eventHandle != null)
                            {
                                eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.Msg, msg, SQLString));
                            }
                            return obj;
                        }
                    }
                    catch (SQLiteException e)
                    {
                        msg = "Execute SQL Error Message: " + e.Message;
                        if (eventHandle != null)
                        {
                            eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.ErrorSql, msg, SQLString));
                        }
                        connection.Close();
                        return null;
                    }
                    finally
                    {
                        connection.Close();
                        cmd.Dispose();
                    }
                    
                }
            }
        }

        /// <summary>
        /// 執行多條SQL語句,實現數據庫事務
        /// </summary>
        /// <param name="SQLStringList"></param>
        public void ExcuteSqlTran(ArrayList SQLStringList)
        {
            var eventHandle = SQLiteMessageEvent;
            string msg = "";
            using (SQLiteConnection conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;
                SQLiteTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                            msg = "SQL Command: " + strsql + " Excute Success!";
                            if (eventHandle != null)
                            {
                                eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.Msg, msg, strsql));
                            }
                        }
                        else
                        {
                            msg = "Execute SQL Error Message: strsql.Trim().Length=" + strsql.Trim().Length.ToString();
                            if (eventHandle != null)
                            {
                                eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.ErrorSql, msg, strsql));
                            }
                        }
                    }
                    tx.Commit();
                }
                catch (SQLiteException ex)
                {
                    tx.Rollback();
                    msg = "Execute SQL Error Message: " + ex.Message;
                    if (eventHandle != null)
                    {
                        eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.ErrorSql, msg, "[ExcuteSqlTran]"));
                    }
                }
                finally
                {
                    conn.Close();
                    cmd.Dispose();
                }
            }
        }

        /// <summary>
        /// 執行單條SQL語句,返回值(DataTable)
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public DataTable SelectUse(string SQLString)
        {
            var eventHandle = SQLiteMessageEvent;
            string msg = "";


            SQLiteCommand cmd = null;
            SQLiteDataAdapter oda = null;
            SQLiteConnection connection = null;
            DataTable dt;
            try
            {
                connection = new SQLiteConnection(connectionString);
                cmd = new SQLiteCommand(SQLString, connection);
                connection.Open();
                dt = new DataTable();
                cmd.Transaction = connection.BeginTransaction();
                oda = new SQLiteDataAdapter(cmd);
                oda.Fill(dt);


                msg = "SQL Command: " + SQLString + " Excute Success!";
                if (eventHandle != null)
                {
                    eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.Msg, msg, SQLString));
                }


                return dt;


            }
            catch (SQLiteException ex)
            {
                msg = "Execute SQL Error Message: " + ex.Message;
                if (eventHandle != null)
                {
                    eventHandle(null, new SQLiteMessageEventArg(SQLiteMessageType.ErrorSql, msg, SQLString));
                }
                return null;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
                oda.Dispose();
            }
        }

        /// <summary>
        /// 測試DB連接
        /// </summary>
        /// <returns></returns>
        public bool ConnectConfirm()
        {
            var sqlStr = "select 1+1 from A";   //A是SQLite DB中的表
            var result = SelectUse(sqlStr);
            if (result != null)
            {
                if (result.Rows.Count == 0)
                {
                    return false;
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    
    }

/// <summary>
    /// 回復事件
    /// </summary>
    public class SQLiteMessageEventArg:EventArgs
    {
        public SQLiteMessageType EventId { get; private set; }


        public string EventData{get;private set;}


        public string SqlCommand { get; private set; }


        public SQLiteMessageEventArg(SQLiteMessageType type, string data, string StrSql)
        {
            EventId = type;
            EventData = data;
            SqlCommand = StrSql;
        }
    }


    public enum SQLiteMessageType
    {
        None = 0,
        Info = 1,
        Msg = 2,
        Error = 3,
        ErrorSql = 4,
        ConnectBroken = 5,
        Others = 9
    }

//=======================主界面================================
        static void Main(string[] args)
        {
            bHelperSQLite _DB = new DbHelperSQLite();
            _DB.SQLiteMessageEvent += new EventHandler<SQLiteMessageEventArg>(_DB_SQLiteMessageEvent);
            string _sql = "select Seq,cstid,D_Time,flag from w_CSTinfo";
            DataTable _dt=_DB.SelectUse(_sql);
	    ... ...
        }

        /// <summary>
        /// DB執行對象返回事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _DB_SQLiteMessageEvent(object sender, SQLiteMessageEventArg e)
        {
            switch (e.EventId)
            { 
                case SQLiteMessageType.Msg:
                    MessageBox.Show(e.EventData);
                    break;
                case SQLiteMessageType.Error:
                    MessageBox.Show(e.EventData + ", SQL: " + e.SqlCommand);
                    break;
                case SQLiteMessageType.ErrorSql:
                    MessageBox.Show(e.EventData);
                    break;
                default:
                    break;
            }
        }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 以下是一个使用 WinForms 程序操作 SQLite 数据库的示例源码: ```csharp using System; using System.Data.SQLite; using System.Windows.Forms; namespace SQLiteDemo { public partial class MainForm : Form { private SQLiteConnection connection; private SQLiteCommand command; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { // 连接到 SQLite 数据库 connection = new SQLiteConnection("Data Source=database.db;Version=3;"); connection.Open(); command = new SQLiteCommand(connection); // 创建表格 command.CommandText = "CREATE TABLE IF NOT EXISTS Person (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; command.ExecuteNonQuery(); } private void btnAdd_Click(object sender, EventArgs e) { // 插入数据 string name = tbName.Text; int age = Convert.ToInt32(tbAge.Text); command.CommandText = "INSERT INTO Person (Name, Age) VALUES (@name, @age)"; command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@age", age); command.ExecuteNonQuery(); MessageBox.Show("数据已添加成功!"); } private void btnDisplay_Click(object sender, EventArgs e) { // 显示数据 command.CommandText = "SELECT * FROM Person"; using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int id = Convert.ToInt32(reader["Id"]); string name = reader["Name"].ToString(); int age = Convert.ToInt32(reader["Age"]); MessageBox.Show($"ID: {id}\nName: {name}\nAge: {age}"); } } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // 关闭数据库连接 command.Dispose(); connection.Close(); } } } ``` 这个示例中,我们创建了一个名为 `MainForm` 的窗体,包含了用于输入名称和年龄的文本框,以及用于添加和显示数据的按钮。在窗体加载时,我们首先连接到 SQLite 数据库并创建了一个名为 `Person` 的表格。通过点击“添加”按钮,我们可以将输入的名称和年龄插入到数据库中。点击“显示”按钮,我们会从数据库中查询所有的数据,并在弹出消息框中显示出来。 ### 回答2: 下面是一个使用Winform程序操作SQLite数据库的示例代码: ```csharp using System; using System.Data.SQLite; using System.Windows.Forms; namespace WinformSQLiteDemo { public partial class MainForm : Form { private SQLiteConnection _conn; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { // 创建数据库连接 _conn = new SQLiteConnection("Data Source=MyDatabase.db;Version=3;"); _conn.Open(); // 创建表 string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; SQLiteCommand createTableCmd = new SQLiteCommand(createTableQuery, _conn); createTableCmd.ExecuteNonQuery(); // 查询并显示数据 string selectQuery = "SELECT * FROM Users"; SQLiteCommand selectCmd = new SQLiteCommand(selectQuery, _conn); SQLiteDataReader reader = selectCmd.ExecuteReader(); while (reader.Read()) { string name = reader.GetString(1); int age = reader.GetInt32(2); dataGridView.Rows.Add(name, age); } // 关闭连接 reader.Close(); _conn.Close(); } private void addButton_Click(object sender, EventArgs e) { string name = nameTextBox.Text; int age = Convert.ToInt32(ageTextBox.Text); // 插入数据 _conn.Open(); string insertQuery = "INSERT INTO Users (Name, Age) VALUES (@name, @age)"; SQLiteCommand insertCmd = new SQLiteCommand(insertQuery, _conn); insertCmd.Parameters.AddWithValue("@name", name); insertCmd.Parameters.AddWithValue("@age", age); insertCmd.ExecuteNonQuery(); // 更新DataGridView dataGridView.Rows.Add(name, age); // 清除输入框 nameTextBox.Text = ""; ageTextBox.Text = ""; _conn.Close(); } } } ``` 这个示例代码包含一个主窗体(MainForm),它在加载时创建了一个SQLite数据库连接,并创建了一个名为"Users"的表。在加载时,它还从数据库中读取已有的用户数据,并将其显示在一个DataGridView控件中。 在窗体中还有一个添加按钮(addButton),当用户输入姓名和年龄后点击此按钮,程序将把数据插入到数据库中,并更新DataGridView以显示新添加的数据。 请注意,该示例中的数据库文件名为"MyDatabase.db",你可以根据需要修改它。 ### 回答3: 以下是一个用于操作SQLite数据库的WinForm程序的示例源代码: ```csharp using System; using System.Data; using System.Data.SQLite; using System.Windows.Forms; namespace SQLiteDemo { public partial class MainForm : Form { private SQLiteConnection connection; private SQLiteCommand command; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { string connectionString = "Data Source=database.db;Version=3;"; connection = new SQLiteConnection(connectionString); command = new SQLiteCommand(connection); connection.Open(); CreateSampleTable(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { connection.Close(); connection.Dispose(); } private void CreateSampleTable() { string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; command.CommandText = createTableQuery; command.ExecuteNonQuery(); } private void btnInsert_Click(object sender, EventArgs e) { string name = txtName.Text; int age = Convert.ToInt32(txtAge.Text); string insertQuery = $"INSERT INTO Users (Name, Age) VALUES ('{name}', {age})"; command.CommandText = insertQuery; command.ExecuteNonQuery(); MessageBox.Show("数据插入成功!"); LoadData(); } private void btnDelete_Click(object sender, EventArgs e) { int id = Convert.ToInt32(txtId.Text); string deleteQuery = $"DELETE FROM Users WHERE Id = {id}"; command.CommandText = deleteQuery; command.ExecuteNonQuery(); MessageBox.Show("数据删除成功!"); LoadData(); } private void btnUpdate_Click(object sender, EventArgs e) { int id = Convert.ToInt32(txtId.Text); string name = txtName.Text; int age = Convert.ToInt32(txtAge.Text); string updateQuery = $"UPDATE Users SET Name = '{name}', Age = {age} WHERE Id = {id}"; command.CommandText = updateQuery; command.ExecuteNonQuery(); MessageBox.Show("数据更新成功!"); LoadData(); } private void LoadData() { string selectQuery = "SELECT * FROM Users"; SQLiteDataAdapter adapter = new SQLiteDataAdapter(selectQuery, connection); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); dataGridView.DataSource = dataTable; } } } ``` 这个示例程序创建了一个包含三个字段(Id、Name和Age)的Users表。通过使用不同的按钮,可以插入、删除和更新数据库中的数据。每次操作完成后,数据表将被重新加载到DataGridView控件中以显示更新后的内容。请确保已在程序所在的目录下创建了一个名为database.db的SQLite数据库文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值