C#操作sqlite

C#操作sqlite

在Nuget管理器中找到System.Data.SQLite并导入到项目。

定义全局变量 SQLiteConnection m_dbConnection指定使用的数据库名,变量SQLiteCommand用来执行相应SQL命令。

如下示例实现了窗体Load事件时的读取数据库相应数值,以及关闭窗体后更新相应数值的操作。

private void Form1_Load(object sender, EventArgs e)
{
    m_dbConnection = new SQLiteConnection("Data Source=uiparams.db;Version=3;");
    m_dbConnection.Open();
    Dictionary<string, string> uikvs = new Dictionary<string, string>();
    string sql = "select * from param ";
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    SQLiteDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        uikvs[ (string)reader["keyname"] ] = (string)reader["val"];
    }
    numericUpDown1.Value = Convert.ToDecimal(uikvs["clicktimes"]);
    numericUpDown2.Value = Convert.ToDecimal(uikvs["clickperiod"]);
    numericUpDown3.Value = Convert.ToDecimal(uikvs["shotdelay"]);
    leftUpperX.Text = uikvs["upperleftx"];
    leftUpperY.Text = uikvs["upperlefty"];
    regionWidth.Text = uikvs["regionwidth"];
    regionHeight.Text = uikvs["regionheight"];
    m_dbConnection.Close();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    m_dbConnection = new SQLiteConnection("Data Source=uiparams.db;Version=3;");
    m_dbConnection.Open();
    Dictionary<string, string> uikvs = new Dictionary<string, string>();
    string sql = "select * from param ";
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    SQLiteDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        uikvs[(string)reader["keyname"]] = (string)reader["val"];
    }
    uikvs["clicktimes"] = numericUpDown1.Value.ToString();
    uikvs["clickperiod"] = numericUpDown2.Value.ToString();
    uikvs["shotdelay"] = numericUpDown3.Value.ToString();
    uikvs["upperleftx"] = leftUpperX.Text;
    uikvs["upperlefty"] = leftUpperY.Text;
    uikvs["regionwidth"] = regionWidth.Text;
    uikvs["regionheight"] = regionHeight.Text;
    foreach(var it in uikvs.Keys)
    {
        sql = String.Format("update param set val = '{0}' where keyname = '{1}'", uikvs[it], it);
        command = new SQLiteCommand(sql, m_dbConnection);
        command.ExecuteReader();
    }
    m_dbConnection.Close();
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注