Created
November 30, 2010 05:01
-
-
Save noqisofon/721182 to your computer and use it in GitHub Desktop.
C# で sqlite を扱うデモ。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.SQLite; | |
using System.IO; | |
namespace sample.demo.sqlite3 { | |
/// <summary> | |
/// | |
/// </summary> | |
class SqliteSample { | |
/// <summary> | |
/// | |
/// </summary> | |
/// <param name="args"></param> | |
public void run(string[] args) { | |
using ( SQLiteConnection connection = new SQLiteConnection( "Data Source=./places.db" ) ) { | |
connection.Open(); | |
SQLiteCommand command = connection.CreateCommand(); | |
// テーブル、histories があるかどうかを調べます。 | |
command.CommandText = "select count(*) from sqlite_master where type = 'table' and name = 'histories'"; | |
long exists = (long)command.ExecuteScalar(); | |
if ( exists == 0 ) { | |
// テーブルの作成を行います。 | |
command.CommandText = "create table histories ( id integer primary key, url nvarchar(512) )"; | |
command.ExecuteNonQuery(); | |
/* | |
* histories.txt は URL のリストです。 | |
* | |
* histories.txt の作り方 | |
* ========================================================================= | |
* Opera((10.63)) の履歴を「全て選択」し、テキストファイルにコピペするだけの簡単な作業です。 | |
* | |
*/ | |
FileStream stream = File.Open( "./histories.txt", FileMode.Open ); | |
/* | |
* histories.txt を histories テーブルに格納します。 | |
*/ | |
using ( StreamReader reader = new StreamReader( stream ) ) { | |
string line; | |
while ( ( line = reader.ReadLine() ) != null ) { | |
line = line.Replace( "'", "%39" ); | |
command.CommandText = string.Format( "insert into histories (url) values ('{0}')", line ); | |
Console.WriteLine( command.CommandText ); | |
command.ExecuteNonQuery(); | |
} | |
} | |
} | |
// select でテーブルの中身を見てみます。 | |
command.CommandText = "select * from histories"; | |
using ( SQLiteDataReader reader = command.ExecuteReader() ) { | |
while ( reader.Read() ) { | |
Console.WriteLine( "{0}", reader["url"] ); | |
} | |
} | |
Console.ReadLine(); | |
} | |
} | |
/// <summary> | |
/// | |
/// </summary> | |
/// <param name="args"></param> | |
static void Main(string[] args) { | |
SqliteSample progn = new SqliteSample(); | |
progn.run( args ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment