SQLiteデータベースを操作
今回はポンコツ2人組がC#のWPFでSQLiteデータベースを操作するプログラムに挑戦してみました! 開発環境はVisualStudio2019を使用し、NuGetパッケージマネージャーで「System.Data.SQLite」をインストールしています。 C#初心者が制作したものなのでいろいろとおかしい部分が多いと思います。プログラムを流用する際は適宜修正してください。
MainWindow.xaml
挿入(Insert)、更新(Update)、削除(Delete)、検索(Select)を実行する各ボタンを配置しています。
検索結果のデータ表示にはDataGridを使用しています。
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SQLite Sample" Height="350" Width="525">
<Grid>
<DataGrid x:Name="dataGrid" AutoGenerateColumns="True" HorizontalAlignment="Left" Height="200" Margin="10,10,0,0" VerticalAlignment="Top" Width="480"/>
<Button Content="Insert" HorizontalAlignment="Left" Margin="10,220,0,0" VerticalAlignment="Top" Width="75" Click="Insert_Click"/>
<Button Content="Update" HorizontalAlignment="Left" Margin="100,220,0,0" VerticalAlignment="Top" Width="75" Click="Update_Click"/>
<Button Content="Delete" HorizontalAlignment="Left" Margin="190,220,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click"/>
<Button Content="Select" HorizontalAlignment="Left" Margin="280,220,0,0" VerticalAlignment="Top" Width="75" Click="Select_Click"/>
</Grid>
</Window>
MainWindow.xaml.cs
コードビハインドでSQLiteの操作を行います。
このコードではアプリケーションの起動時にデータベースとテーブルを作成しており、
データベースはプロジェクトの実行ディレクトリに「sample.db」という名前で作成されます。
作成されたSampleTableテーブルには連番を自動採番するIdカラム、文字列型のName列、数値型のAgeカラムが用意されています。
アプリケーションは作成したSQLiteデータベースに対して、Insert、Update、Delete、Select操作を行っています。
更新系の操作では、トランザクションを使用し、エラーが発生した場合はロールバックしています。
using System;
using System.Data;
using System.Data.SQLite;
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
private const string ConnectionString = "Data Source=sample.db";
public MainWindow()
{
InitializeComponent();
InitializeDatabase();
}
private void InitializeDatabase()
{
using (var connection = new SQLiteConnection(ConnectionString))
{
connection.Open();
string createTableQuery = @"
CREATE TABLE IF NOT EXISTS SampleTable (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Age INTEGER NOT NULL
)";
using (var command = new SQLiteCommand(createTableQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
private void Insert_Click(object sender, RoutedEventArgs e)
{
ExecuteNonQueryWithTransaction("INSERT INTO SampleTable (Name, Age) VALUES ('ポンコツ女子', 20)");
SelectProc();
MessageBox.Show("新規登録しました");
}
private void Update_Click(object sender, RoutedEventArgs e)
{
ExecuteNonQueryWithTransaction("UPDATE SampleTable SET Age = 21 WHERE Name = 'ポンコツ女子'");
SelectProc();
MessageBox.Show("更新しました");
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
ExecuteNonQueryWithTransaction("DELETE FROM SampleTable WHERE Name = 'ポンコツ女子'");
SelectProc();
MessageBox.Show("削除しました");
}
private void Select_Click(object sender, RoutedEventArgs e)
{
SelectProc();
}
private void SelectProc()
{
DataTable dt = ExecuteQuery("SELECT * FROM SampleTable");
dataGrid.ItemsSource = dt.DefaultView;
}
private void ExecuteNonQueryWithTransaction(string query)
{
using (var connection = new SQLiteConnection(ConnectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
using (var command = new SQLiteCommand(query, connection))
{
command.ExecuteNonQuery();
}
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show($"Error: {ex.Message}");
}
}
}
}
private DataTable ExecuteQuery(string query)
{
using (var connection = new SQLiteConnection(ConnectionString))
{
connection.Open();
using (var command = new SQLiteCommand(query, connection))
{
using (var adapter = new SQLiteDataAdapter(command))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}
}
}
}
以下が実行した結果です。上手く動作していますね。
・1枚目:インサートした結果
・2枚目:アップデートした結果
・3枚目:デリートした結果
以下は作成されたデータベースの場所です。
もしデータベースファイルを特定のディレクトリに作成したい場合は、フルパスを指定することもできます。
例えば、デスクトップに作成したい場合は以下のように接続文字列を変更します。
Windowsのユーザー名部分やパスは自分の環境に合わせて適宜変更してください。
private const string ConnectionString = @"Data Source=C:\Users\ユーザー名\Desktop\sample.db";
今回のサンプルコードは以上ですが、SQLiteデータベースを操作するプログラムは理解できましたか?
あまり理解できなかった人は実際にプログラムを書いて実行し、いろいろ試してみてください。 アプリケーションからデータベースを操作する機会は多いので、頑張ってマスターして下さいね!