0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLite3のデータをコマンドラインから操作してみる

Last updated at Posted at 2025-10-06

はじめに

前回はSQL Server LocalDBを使ってみましたが、Linuxでは使えないためSQLite3のデータをコマンドラインから操作してみます。

以下のような使い方を想定しています。


$ sqlite3 myop.db
SQLite version 3.45.1 2024-01-30 16:01:20
Enter ".help" for usage hints.
sqlite> .schema users
CREATE TABLE users(id char(256) primary key,email char(256) unique,password char(256),updated datetime DEFAULT CURRENT_TIMESTAMP);

実行環境

下記バージョンで動作確認しています。

  • WSL2(Ubuntu)
  • .NET 10.0

$ dotnet --version
10.0.100-rc.1.25451.107

学習方針

SQLite3で開発する事で、Windows/Mac/Linuxにおいてもそのままできると思います。


$ mkdir dbtool
$ cd dbtool
$ dotnet new console

まずは実行してみます。


$ dotnet run
Hello World!

必要なパッケージをインストールします。


$ dotnet add package System.Data.SQLite.Core

以下のような使い方を想定しています。



$ dbtool

Usage: dbtool -options [file path]

options
    -e          export user from SQLite
    -i          import user to SQLite
    -d          delete user from SQLite
    -v          display version
    -h          display help message

$ dbtool -v

SQLite module: version 201910

$ dbtool -e users.txt

$ cat users.txt
id      email   password        updated
000000  bbb@bbb.com     password        2025-10-06 11:45:45
000001  aaa@bbb.com     password        2025-10-06 11:45:45
Program.cs
using System;
using System.IO;
using System.Text;
using System.Data.SQLite;

namespace dbtool
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length<1 || args.Length>2) {
                help();
                return;
            }
            if (args.Length==1) {
                switch(args[0])
                {
                    case "-v": version();break;
                    default: help();break;
                }
                return;
           }
           switch(args[0])
           {
                case "-i": import(args[1]);break;
                case "-e": export(args[1]);break;
                case "-d": delete(args[1]);break;
                default: help();break;
           }
           return;
        }
        static void import(string param)
        {
            string sqlcmd;
            var sqlConnectionSb = new SQLiteConnectionStringBuilder { DataSource = "myop.db" };
            using (var cn = new SQLiteConnection(sqlConnectionSb.ToString()))
            {
                cn.Open();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                using (StreamReader sr = new StreamReader(new FileStream(@param, FileMode.Open), Encoding.GetEncoding("shift_jis")))
                {
                    while(sr.Peek() >0){
                        String line = sr.ReadLine();
                        string[] values =  line.Split('\t');
                        if (values[0]=="id") {
                            continue;
                        } else {
                            sqlcmd = "REPLACE INTO users (id, email, password, updated) VALUES ('" + values[0]+"','"+values[1]+"','"+values[2]+"',datetime('"+values[3]+"'))";
                        }
                        using (SQLiteTransaction trans = cn.BeginTransaction())
                        {
                            SQLiteCommand cmd = cn.CreateCommand();
                            cmd.CommandText = sqlcmd;
                            cmd.ExecuteNonQuery();
                            trans.Commit();
                        }
                    }
                }
                cn.Close();
            }
            return;
        }
        static void export(string param)
        {
            var sqlConnectionSb = new SQLiteConnectionStringBuilder { DataSource = "myop.db" };
            using (var cn = new SQLiteConnection(sqlConnectionSb.ToString()))
            {
                cn.Open();
                using (var cmd = new SQLiteCommand(cn))
                {
                    cmd.CommandText = "SELECT * FROM users";
                    using (SQLiteDataReader reader = cmd.ExecuteReader())
                    {
                        string message = "id\temail\tpassword\tupdated\r\n";
                        while (reader.Read())
                        {
                            DateTime dt = DateTime.Parse(reader["updated"].ToString());
                            message += reader["id"].ToString() + "\t" + reader["email"].ToString() + "\t" + reader["password"].ToString() + "\t" + dt.ToString("yyyy-MM-dd hh:mm:ss") + "\r\n";
                        }
                        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                        File.WriteAllText(@param, message, Encoding.GetEncoding("shift_jis"));
                    }
                }
                cn.Close();
            }
            return;
        }
        static void delete(string param)
        {
            var sqlConnectionSb = new SQLiteConnectionStringBuilder { DataSource = "myop.db" };
            using (var cn = new SQLiteConnection(sqlConnectionSb.ToString()))
            {
                cn.Open();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                using (StreamReader sr = new StreamReader(new FileStream(@param, FileMode.Open), Encoding.GetEncoding("shift_jis")))
                {
                    while(sr.Peek() >0){
                        string id = sr.ReadLine();
                        if (id=="id") continue;
                        string sqlcmd = "DELETE FROM USERS WHERE id = '" + id +"'";
                        using (SQLiteTransaction trans = cn.BeginTransaction())
                        {
                            SQLiteCommand cmd = cn.CreateCommand();
                            cmd.CommandText = sqlcmd;
                            cmd.ExecuteNonQuery();
                            trans.Commit();
                        }
                    }
                }
                cn.Close();
            }
            return;
        }
        static void version()
        {
            Console.WriteLine("\nSQLite module: version 201910\n");
            return;
        }
        static void help()
        {

            Console.WriteLine("\nUsage: dbtool -options [file path]\n");

            Console.WriteLine("options");
            Console.WriteLine("    -e          export user from SQLite");
            Console.WriteLine("    -i          import user to SQLite");
            Console.WriteLine("    -d          delete user from SQLite");
            Console.WriteLine("    -v          display version");
            Console.WriteLine("    -h          display help message\n");
            return;
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?