C#访问Sqlite入门之基本增删改查操作

界面

C#访问Sqlite入门之基本增删改查操作

; 代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;

namespace SqliteTest
{
public partial class Form1 : Form
{
SQLiteConnection Conn;

    public Form1()
    {
        InitializeComponent();
    }

    #region 操作库
    private void btnOpenDatabase_Click(object sender, EventArgs e)
    {
        OpenDatabase();
        comboBox2.Text = "";
        MessageBox.Show("打开成功!");
    }

    private void btnCloseDatabase_Click(object sender, EventArgs e)
    {
        if (Conn == null)
        {
            MessageBox.Show("数据库未打开");
        }
        else
        {
            Conn.Close();
            MessageBox.Show("关闭成功!");
        }
    }

    private void btnCreateDatabase_Click(object sender, EventArgs e)
    {
        CreateDatabase();
    }

    private void OpenDatabase()
    {
        string FilePath = Application.StartupPath + "\\" + comboBox1.Text + ".db";
        try
        {
            Conn = new SQLiteConnection("Data Source=" + FilePath + ";Version=3;");
            Conn.Open();
        }
        catch (Exception ex)
        {
            throw new Exception("打开数据库:" + FilePath + "的连接失败:" + ex.Message);
        }
    }

    private void CreateDatabase()
    {
        string FilePath = Application.StartupPath + "\\" + comboBox1.Text + ".db";
        if (!File.Exists(FilePath))
        {
            SQLiteConnection.CreateFile(FilePath);
        }
    }

    private bool CheckDatabaseIsOpen()
    {
        if (Conn != null && Conn.State == ConnectionState.Open)
        {
            return true;
        }
        else
        {
            MessageBox.Show("数据库未打开!");
            return false;
        }
    }
    #endregion

    #region 操作表
    private void btnCreateDataTable_Click(object sender, EventArgs e)
    {
        if (CheckDatabaseIsOpen())
        {
            CreateDataTable();
        }
    }

    private void btnDelDataTable_Click(object sender, EventArgs e)
    {
        if (CheckDatabaseIsOpen())
        {
            DropDataTable();
        }
    }

    private void comboBox2_DropDown(object sender, EventArgs e)
    {
        if (CheckDatabaseIsOpen())
        {
            comboBox2.DataSource = QueryTableName();
        }
    }

    private List<string> QueryTableName()
    {
        List<string> list = new List<string>();
        try
        {
            //string sql = "select * from " + textBox2.Text + " order by score desc";
            string sql = "select name from sqlite_master where type='table' order by name";
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                list.Add(reader["name"].ToString());
            }
        }
        catch (Exception ex)
        {
            throw new Exception("&#x67E5;&#x8BE2;&#x6570;&#x636E;&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
        return list;
    }

    private void CreateDataTable()
    {
        try
        {
            string sql = "create table " + comboBox2.Text + " (name varchar(20), score varchar(20))";
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("&#x521B;&#x5EFA;&#x6570;&#x636E;&#x8868;" + comboBox2.Text + "&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
        MessageBox.Show("&#x521B;&#x5EFA;&#x6570;&#x636E;&#x8868;" + comboBox2.Text + "&#x6210;&#x529F;&#xFF01;");
    }

    private void DropDataTable()
    {
        try
        {
            //string sql = "create table " + comboBox2.Text + " (name varchar(20), score varchar(20))";
            string sql = "drop table if exists "+comboBox2.Text;
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("&#x5220;&#x9664;&#x6570;&#x636E;&#x8868;" + comboBox2.Text + "&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
        MessageBox.Show("&#x5220;&#x9664;&#x6570;&#x636E;&#x8868;" + comboBox2.Text + "&#x6210;&#x529F;&#xFF01;");
    }
    #endregion

    #region &#x6839;&#x636E;&#x6307;&#x5B9A;&#x4F4D;&#x7F6E;&#x62FF;&#x5230;&#x6570;&#x636E;&#x5E93;&#x7684;&#x5E93;&#x540D;
    private void comboBox1_DropDown(object sender, EventArgs e)
    {
        comboBox1.DataSource = GetDatabase();
    }

    private List<string> GetDatabase()
    {
        string FilePath = Application.StartupPath + "\\";
        //&#x8FD9;2&#x884C;&#x6211;&#x4E5F;&#x4E0D;&#x77E5;&#x9053;&#x5B83;&#x4E3A;&#x4EC0;&#x4E48;&#x975E;&#x8981;&#x7528;FileInfo&#xFF0C;&#x5E72;&#x8106;&#x6211;&#x518D;&#x58F0;&#x660E;&#x4E00;&#x4E2A;string&#x7684;&#x597D;&#x4E86;
        List<fileinfo> list = new List<fileinfo>();
        List<fileinfo> list2 = GetFile(FilePath, ".db", list);
        List<string> list3 = new List<string>();
        foreach (FileInfo shpFile in list2)
        {
            list3.Add(shpFile.Name.Replace(".db",""));
        }
        return list3;
    }

    /// <summary>
    /// &#x83B7;&#x5F97;&#x76EE;&#x5F55;&#x4E0B;&#x6240;&#x6709;&#x6587;&#x4EF6;&#x6216;&#x6307;&#x5B9A;&#x6587;&#x4EF6;&#x7C7B;&#x578B;&#x6587;&#x4EF6;(&#x5305;&#x542B;&#x6240;&#x6709;&#x5B50;&#x6587;&#x4EF6;&#x5939;)
    /// </summary>
    /// <param name="path">&#x6587;&#x4EF6;&#x5939;&#x8DEF;&#x5F84;
    /// <param name="extName">&#x6269;&#x5C55;&#x540D;&#x53EF;&#x4EE5;&#x591A;&#x4E2A; &#x4F8B;&#x5982; .mp3.wma.rm
    /// <returns>List<fileinfo></fileinfo></returns>
    public static List<fileinfo> GetFile(string path, string extName, List<fileinfo> lst)
    {
        try
        {
            string[] dir = Directory.GetDirectories(path); //&#x6587;&#x4EF6;&#x5939;&#x5217;&#x8868;
            DirectoryInfo fdir = new DirectoryInfo(path);
            FileInfo[] file = fdir.GetFiles();
            //FileInfo[] file = Directory.GetFiles(path); //&#x6587;&#x4EF6;&#x5217;&#x8868;
            if (file.Length != 0 || dir.Length != 0) //&#x5F53;&#x524D;&#x76EE;&#x5F55;&#x6587;&#x4EF6;&#x6216;&#x6587;&#x4EF6;&#x5939;&#x4E0D;&#x4E3A;&#x7A7A;
            {
                foreach (FileInfo f in file) //&#x663E;&#x793A;&#x5F53;&#x524D;&#x76EE;&#x5F55;&#x6240;&#x6709;&#x6587;&#x4EF6;
                {
                    if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
                    {
                        lst.Add(f);
                    }
                }
                foreach (string d in dir)
                {
                    GetFile(d, extName, lst);//&#x9012;&#x5F52;
                }
            }
            return lst;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    #region &#x589E;&#x5220;&#x6539;&#x67E5;&#x6570;&#x636E;
    private void btnAddData_Click(object sender, EventArgs e)
    {
        InsertData();
    }

    private void btnQueryData_Click(object sender, EventArgs e)
    {
        QueryData();
    }

    private void btnDelData_Click(object sender, EventArgs e)
    {
        DeleteData();
    }

    private void btnUpdateData_Click(object sender, EventArgs e)
    {
        UpdateData();
    }

    private void InsertData()
    {
        try
        {
            string sql = "insert into " + comboBox2.Text + " (name, score) values ('" + textBox1.Text + "', '" + textBox2.Text + "')";
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("&#x63D2;&#x5165;&#x6570;&#x636E;&#xFF1A;" + textBox1.Text + ":" + textBox2.Text + "&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
    }

    private void DeleteData()
    {
        try
        {
            string sql = "delete from " + comboBox2.Text + " where name = " + textBox1.Text;
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("&#x5220;&#x9664;&#x6570;&#x636E;&#xFF1A;" + textBox1.Text + ":" + textBox2.Text + "&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
    }

    private void UpdateData()
    {
        try
        {
            string sql = "update " + comboBox2.Text + " set score = '" + textBox2.Text + "' where name='" + textBox1.Text + "'";
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("&#x66F4;&#x65B0;&#x6570;&#x636E;&#xFF1A;" + textBox1.Text + ":" + textBox2.Text + "&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
    }

    private void QueryData()
    {
        try
        {
            string sql = "select * from " + comboBox2.Text + " order by score desc";
            SQLiteCommand command = new SQLiteCommand(sql, Conn);
            SQLiteDataReader reader = command.ExecuteReader();
            richTextBox1.Text = "";
            while (reader.Read()){
              richTextBox1.AppendText("Name: " + reader["name"] + "\tScore: " + reader["score"] + "\r\n");
            }
        }
        catch (Exception ex)
        {
            throw new Exception("&#x67E5;&#x8BE2;&#x6570;&#x636E;&#x5931;&#x8D25;&#xFF1A;" + ex.Message);
        }
    }
    #endregion
}
</fileinfo></fileinfo></string></string></fileinfo></fileinfo></fileinfo></string></string></string></string>

}

Original: https://blog.csdn.net/GoldenLionKing/article/details/125477888
Author: GoldenLionKing
Title: C#访问Sqlite入门之基本增删改查操作

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816710/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球