2023年3月
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
無料ブログはココログ

 

« Cool Rabbits | トップページ | 昨日届いたCD »

2010年8月15日 (日)

SQLiteを試してみる

「和魂」でfirefoxのクッキーを参照するためにSQLiteを使用しているけど、ただ、クッキー情報を参照しているだけで(技術的に)面白くない。
もうちょっと本格的にDBとして使ってみたくなった。
たとえば、「和魂」でダウンロードコマンドの登録・結果保存を行うことによってレジュームできるとか、検索結果を保存しておくとか。

Web実験室さんの「C#-SQLiteに接続」を参考(というか丸写し)にして、フォームでクエリーを実行できる試しプログラムを作ってみた。

ここにプロジェクトファイル(Releaseのbinもある)を入れておいたので、ダウンロードしてもらって、SQLiteのDLLをパスの通っているところに置けばOK(だと思う)。
DLL系のエラーが出るようだったら、リビルドしてちょ。
書き忘れてた。Visual C# 2008のプロジェクトです。

んで、以下のSQL文を打ち込んで・・・

create table test1 (f1 char(10), f2 int);
insert into test1 values('aaaa', 1);
insert into test1 values('bbbb', 2);

SELECT文でテーブルの中身がめでたく見られました!

Sqlitetest

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;

namespace SQLiteTest
{
    public partial class Form1 : Form
    {
        SQLiteConnection con_;

        public Form1()
        {
            InitializeComponent();

            con_ = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string query = "";
            string result = "";

            query = textBox1.Text;
            string[] words = query.Trim().Split(' ');

            switch (words[0].ToLower())
            {
                case "select":
                    result = runSelectQuery(query);
                    textBox2.Text = result;
                    break;

                case "delete":
                case "update":
                case "insert":
                case "create":
                case "drop":
                    result = runQuery(query);
                    textBox2.Text = result;
                    break;

                default:
                    textBox2.Text = string.Format("SYNTAX ERROR:\"{0}\"", query);
                    break;
            }
        }

        private string runSelectQuery(string query)
        {
            string result = "";
            string result_format = "";

            if (con_ == null)
            {
                con_ = new SQLiteConnection("Data Source=test.sqlite3");
                con_.Open();
            }

            SQLiteCommand command = new SQLiteCommand(query, con_);
            // データベース接続を開く
            try
            {
                SQLiteDataReader reader;
                reader = command.ExecuteReader();
                int fieldCount = reader.FieldCount;
                for(int i = 0; fieldCount > i; i++)
                {
                    if(i != 0)
                    {
                        result_format += "\t";
                        result += "\t";
                    }
                    result_format += string.Format("{{{0}}}", i);
                    result += reader.GetName(i);
                }
                result += "\r\n----------------\r\n";

                object[] values = new object[fieldCount];

                while (reader.Read())
                {
                    reader.GetValues(values);
                    result += string.Format(result_format, values);
                    result += "\r\n";
                }

                reader.Close();

            }
            catch (Exception e)
            {
                result = string.Format("Exception:{0}", e.ToString());
            }

            return result;
        }

        private string runQuery(string query)
        {
            SQLiteCommand command = null;
            string result = string.Format("RESULT OK:\"{0}\"", query);

            try
            {
                if (con_ == null)
                {
                    con_ = new SQLiteConnection("Data Source=test.sqlite3");
                    con_.Open();
                }

                command = new SQLiteCommand("begin", con_);
                command.ExecuteNonQuery();
                command = new SQLiteCommand(query, con_);
                int row_count = command.ExecuteNonQuery();
                command = new SQLiteCommand("commit", con_);
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                result = string.Format("Exception:{0}", e.ToString());
                command = new SQLiteCommand("rollback", con_);
                command.ExecuteNonQuery();
            }

            return result;
        }

        private void closeDB()
        {
            con_.Close();
            con_.Dispose();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            closeDB();
        }

    }
}

注:お試しプログラムですので、動作は保証しません。本プログラムを使用して被害・損害を受けた、または与えたとしても当方は一切責任を持ちませんのでご了承ください。また、質問 は一切受け付けませんのでご自分で勉強なさったら。まあ、オイラも勉強不足だし、直観とフィーリングでプログラムを作っているので、何が正しいかは己の心 に聞け!

USE AT YOUR OWN RISK


« Cool Rabbits | トップページ | 昨日届いたCD »

コメント

コメントを書く

(ウェブ上には掲載しません)

トラックバック


この記事へのトラックバック一覧です: SQLiteを試してみる:

« Cool Rabbits | トップページ | 昨日届いたCD »