Windows Azure Drive を使う で Azure Drive を作成したので、Azure Drive で SQLiteを試してみました。
例外処理をしていないこともありますが、CloudDrive のマウントを行っているくらいで、.NETからSQLiteを使う場合と、ほとんど同じような感じです。
※サンプルコードは、Windows Azure Drive を使う でAzure Driveを作成済みの環境です。
準備
.NETで書き直しされたSQLite用クラスライブラリである System.Data.SQLite を使っていますので、System.Data.SQLite をダウンロードして、参照設定に追加します。
System.Data.SQLite
http://sqlite.phxsoftware.com/
サンプルコード(テーブル作成)
using System;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Data.SQLite;
namespace WebRole1.Storage
{
public partial class sample2 : System.Web.UI.Page
{
private CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
protected void btnCreate_Click(object sender, EventArgs e)
{
int cacheSize = 500;
LocalResource localCache = RoleEnvironment.GetLocalResource("LocalStorage1");
CloudDrive.InitializeCache(localCache.RootPath + "cache", localCache.MaximumSizeInMegabytes);
CloudDrive drive = account.CreateCloudDrive("vhd/drive1.vhd");
string driveLetter = drive.Mount(cacheSize, DriveMountOptions.None);
string dbConnectionString = string.Format("Data Source={0}", driveLetter + @"\\azure.db");
using (SQLiteConnection cn = new SQLiteConnection(dbConnectionString))
using (SQLiteCommand cmd = cn.CreateCommand())
{
cn.Open();
cmd.CommandText = "CREATE TABLE Personal (id INTEGER PRIMARY KEY, name TEXT)";
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
当たり前ですが、INSERTやSELECTもエンコードなく日本語が使えます。
INSERT
cmd.CommandText = "INSERT INTO Personal (name) VALUES('田中一郎')";
cmd.ExecuteNonQuery();
SELECT
cmd.CommandText = "SELECT * FROM Personal";
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Response.Write(String.Format("id = {0}, name = {1} <br />", reader[0], reader[1]));
}
}