2016年1月15日 星期五

SQLite tutorial

SQLite 是一個功能強大的資料庫 open source,而且安裝空間小,輕巧方便攜帶性高。
SQLite支援列表

編譯環境
Windows7 64bit
.Net Framework 3.5
Microsoft Visual Studio Express 2015 For Windows Desktop

1.下載 ADO.NET 2.0 Provider for SQLite 並安裝它

2.引用 System.Data.SQLite.dll

   32 bit : ../bin/System.Data.SQLite.dll

   64 bit: ../bin/x64/System.Data.SQLite.dll

3.Code


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.IO;// for check file exist
using System.Data.SQLite;//for SQLite

namespace c_sharp_sqlite
{
    public partial class Form1 : Form
    {
        private SQLiteConnection sqlite_connect;
        private SQLiteCommand sqlite_cmd;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!File.Exists(Application.StartupPath + @"\myData.db"))
            {
                SQLiteConnection.CreateFile("myData.db");
            }

            string name = textBox1.Text;
            string phone_number = textBox2.Text;

            sqlite_connect = new SQLiteConnection("Data source=myData.db");
            //建立資料庫連線

            sqlite_connect.Open();// Open
            sqlite_cmd = sqlite_connect.CreateCommand();//create command
            
            sqlite_cmd.CommandText = @"CREATE TABLE IF NOT EXISTS phone (num INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone_number TEXT)";
            //create table header
            //INTEGER PRIMARY KEY AUTOINCREMENT=>auto increase index
            sqlite_cmd.ExecuteNonQuery(); //using behind every write cmd

            sqlite_cmd.CommandText = "INSERT INTO phone VALUES (null, '" + name + "','" + phone_number + "');";
            sqlite_cmd.ExecuteNonQuery();//using behind every write cmd

            sqlite_connect.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sqlite_connect = new SQLiteConnection("Data source=myData.db");
            //建立資料庫連線
            sqlite_connect.Open();// Open
            sqlite_cmd = sqlite_connect.CreateCommand();//create command

            sqlite_cmd.CommandText = "SELECT * FROM phone"; //select table

            SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();

            while (sqlite_datareader.Read()) //read every data
            {
                String name_load = sqlite_datareader["name"].ToString();
                String phone_number_load = sqlite_datareader["phone_number"].ToString();
                MessageBox.Show(name_load + ":" + phone_number_load);
            }
            sqlite_connect.Close();
        }
    }
}

沒有留言:

張貼留言