using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//createNewDatabase();
connectToDatabase();
SQLiteDataReader reader = printHighscores();
while (reader.Read())
{
foreach (Control item in Controls)
{
if (item is TextBox)
{
if (reader["name"].ToString() == item.Name)
{
item.Text = reader["score"].ToString();
}
}
if (item is CheckBox)
{
if (reader["name"].ToString() == item.Name)
{
CheckBox tx = item as CheckBox;
tx.Checked = Convert.ToBoolean(reader["score"]);
}
}
if (item is NumericUpDown)
{
if (reader["name"].ToString() == item.Name)
{
NumericUpDown tx = item as NumericUpDown;
tx.Value = Convert.ToDecimal(reader["score"]);
}
}
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
delecttable();
createTable();
foreach (Control item in Controls)
{
if (item is CheckBox)
{
CheckBox c = item as CheckBox;
fillTable(c.Name, c.Checked.ToString());
}
if (item is TextBox)
{
fillTable(item.Name, item.Text);
}
if (item is NumericUpDown)
{
NumericUpDown c = item as NumericUpDown;
fillTable(c.Name, c.Value.ToString());
}
}
}
//数据库连接
public static SQLiteConnection m_dbConnection;
//创建一个空的数据库
public static void createNewDatabase()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
}
//创建一个连接到指定数据库
public static void connectToDatabase()
{
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
}
//在指定数据库中创建一个table
public static void createTable()
{
string sql = "create table highscores (name varchar(20), score varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
//插入一些数据
public static void fillTable(string s1, string s2)
{
string sql = "insert into highscores (name, score) values ('" + s1 + "', '" + s2 + "')";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
public static void delecttable()
{
string sql = "DROP TABLE highscores";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
//使用sql查询语句,并显示结果
public static SQLiteDataReader printHighscores()
{
string sql = "select * from highscores";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
return command.ExecuteReader();
}
}
}