1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C# postgres連携コード

Posted at
Form1.cs
using System.Data;
using System.Diagnostics;
using System.Data.SQLite;
using Microsoft.Data.Sqlite;
using System.Globalization;

namespace DB_SQLite1
{
    public partial class Form1 : Form
    {

        int selectedRowIndex = 0;

        public Form1()
        {
            InitializeComponent();
        }

        // プロパティを使って子フォームからアクセスできるようにする
        // ■thisとこれがないとサブフォームからアクセスできない(重要)■
        //public string TextBoxValue
        //{
        //    get { return textBox1.Text; }
        //    set { textBox1.Text = value; }
        //}

        //■追加ボタン押下
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(this,"新規");
            form2.ShowDialog();
            UpdateList();
        }

        //■終了ボタン押下
        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //初回表示
        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateList();
        }

        //DataGridView更新処理
        public void UpdateList()
        {
            // 接続先情報(bin/Debugフォルダ内に「test.sqlite」という名前でDBが作成される)
            var connectionString = "Data Source=test.sqlite";

            // 接続やSQL実行に必要なインスタンスの生成
            using (var connection = new SQLiteConnection(connectionString))
            using (var command = connection.CreateCommand())
            {
                // 接続開始
                connection.Open();

                // SELECT文の実行
                command.CommandText = "SELECT * FROM users;";

                using (var reader = command.ExecuteReader())
                {
                    //データテーブル作成
                    var dt = new DataTable();
                    //データテーブルにSQL結果読み込み
                    dt.Load(reader);
                    //データグリッドビューとデータテーブルバインド
                    this.dataGridView1.DataSource = dt;

                    // 結果を表示
                    foreach (var row in dt.AsEnumerable())
                        Debug.WriteLine($"TestData---, {row["name"]}");
                }
            }
        }

        //■更新ボタン押下
        private void button5_Click(object sender, EventArgs e)
        {
            UpdateList();
        }

        //■削除ボタン押下
        private void button3_Click(object sender, EventArgs e)
        {

            string selectedValue = "";

            // 現在選択されている行があるかどうか確認
            if (dataGridView1.CurrentRow != null)
            {
                // 選択された行のインデックスを取得
                int selectedRowIndex = dataGridView1.CurrentRow.Index;

                // 選択された行の特定のセルの値を取得
                selectedValue = dataGridView1.Rows[selectedRowIndex].Cells["id"].Value.ToString();

                // 値を使った処理(例: メッセージボックスに表示)
                MessageBox.Show($"選択されたID: {selectedValue}");
            }
            else
            {
                // 行が選択されていない場合のエラーメッセージ
                MessageBox.Show("行が選択されていません。");
                return;
            }

            // メッセージボックスを表示し、Yes/Noを選択
            DialogResult result = MessageBox.Show("本当に実行しますか?", "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            // クリックされたボタンに応じた分岐処理
            if (result == DialogResult.No)
            {
                // Noがクリックされた場合の処理
                MessageBox.Show("キャンセルされました。");
                return;
            }

            //■以下DB削除処理
            // 接続先情報(bin/Debugフォルダ内に「test.sqlite」という名前でDBが作成される)
            var connectionString = "Data Source=test.sqlite";

            // 接続やSQL実行に必要なインスタンスの生成
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // データを削除する
                string sql = "DELETE FROM users WHERE id = @id";
                using (var command = new SQLiteCommand(sql, connection))
                {
                    // パラメータに値を追加
                    command.Parameters.AddWithValue("@id", selectedValue);

                    // クエリを実行
                    command.ExecuteNonQuery();
                }

            }

            //データグリッドビュー更新
            UpdateList();

            MessageBox.Show("削除しました");
        }

        //■変更ボタン押下
        private void button2_Click(object sender, EventArgs e)
        {
            string selectedValue = "";

            // 選択された行のインデックスを取得
            int selectedRowIndex = dataGridView1.CurrentRow.Index;


            // 現在選択されている行があるかどうか確認
            if (dataGridView1.CurrentRow != null)
            {

                // 選択された行の特定のセルの値を取得
                selectedValue = dataGridView1.Rows[selectedRowIndex].Cells["id"].Value.ToString();

                // 値を使った処理(例: メッセージボックスに表示)
                MessageBox.Show($"選択されたID: {selectedValue}");
            }
            else
            {
                // 行が選択されていない場合のエラーメッセージ
                MessageBox.Show("行が選択されていません。");
                return;
            }


            Form2 form2 = new Form2(this,"変更");

            //プロパティやメソッド経由でアクセスする方法
            form2.TextBoxValue1 = dataGridView1.Rows[selectedRowIndex].Cells["class"].Value.ToString();
            form2.TextBoxValue2 = dataGridView1.Rows[selectedRowIndex].Cells["name"].Value.ToString();
            form2.TextBoxValue3 = dataGridView1.Rows[selectedRowIndex].Cells["cost"].Value.ToString();
            form2.TextBoxValue4 = dataGridView1.Rows[selectedRowIndex].Cells["id"].Value.ToString();

            form2.ShowDialog();
            UpdateList();

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
Form2.cs

using System.Data.SQLite; // System.Data.SQLiteを使用

namespace DB_SQLite1
{
    public partial class Form2 : Form
    {
        Form1 _form1;
        private string _checkBtn;
        private string _id;

        public Form2(Form1 form1 , string checkBtn)
        {
            InitializeComponent();
            _form1 = form1;
            _checkBtn = checkBtn;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //■新規登録処理
            if (_checkBtn == "新規")
            {
                    MessageBox.Show("新規が押されました");
                // 必要なフィールドが入力されているか確認
                if (bunrui.Text == "" || hinmei.Text == "" || kingaku.Text == "0")
                {
                    MessageBox.Show("適切に登録してください");
                    return;
                }

                // 接続先情報(bin/Debugフォルダ内に「test.sqlite」という名前でDBが作成される)
                var connectionString = "Data Source=test.sqlite";

                // 接続やSQL実行に必要なインスタンスの生成
                using (var connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();

                    // SQL文を準備
                    string sql = "INSERT INTO users (class, name, cost, date) VALUES (@class, @name, @cost, @date);";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        // パラメータに値を追加
                        command.Parameters.AddWithValue("@class", bunrui.Text);  // bunrui.ItemsからTextに修正
                        command.Parameters.AddWithValue("@name", hinmei.Text);
                        command.Parameters.AddWithValue("@cost", kingaku.Text);
                        command.Parameters.AddWithValue("@date", calendar1.SelectionRange.Start.ToString("yyyy-MM-dd"));  // 日付をフォーマットして格納

                        // クエリを実行
                        command.ExecuteNonQuery();
                    }

                    MessageBox.Show("登録しました");
                    // Form1の更新メソッドを呼び出す

                }
            }

            //■変更登録処理
            if (_checkBtn == "変更")
            {
                MessageBox.Show("変更が押されました");
               

                // 必要なフィールドが入力されているか確認
                    if (bunrui.Text == "" || hinmei.Text == "" || kingaku.Text == "0")
                {
                    MessageBox.Show("適切に登録してください");
                    return;
                }

                // 接続先情報(bin/Debugフォルダ内に「test.sqlite」という名前でDBが作成される)
                var connectionString = "Data Source=test.sqlite";

                // 接続やSQL実行に必要なインスタンスの生成
                using (var connection = new SQLiteConnection(connectionString))
                {

                    // SQL文を準備
                    string sql = "UPDATE users SET class = @class , name = @name , cost = @cost , date = @date  WHERE id = @id";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        // パラメータに値を追加
                        command.Parameters.AddWithValue("@class", bunrui.Text);  // bunrui.ItemsからTextに修正
                        command.Parameters.AddWithValue("@name", hinmei.Text);
                        command.Parameters.AddWithValue("@cost", kingaku.Text);
                        command.Parameters.AddWithValue("@date", calendar1.SelectionRange.Start.ToString("yyyy-MM-dd"));
                        command.Parameters.AddWithValue("@id", _id);

                        //MessageBox.Show("_id"+_id);
                        connection.Open();
                        command.ExecuteNonQuery();
                    }


                }
            }
        }

        public string TextBoxValue1
        {
            get { return bunrui.Text; }
            set { bunrui.Text = value; }
        }
        public string TextBoxValue2
        {
            get { return hinmei.Text; }
            set { hinmei.Text = value; }
        }
        public string TextBoxValue3
        {
            get { return kingaku.Text; }
            set { kingaku.Text = value; }
        }
        public string TextBoxValue4
        {
            get { return _id; }
            set { _id = value; }
        }

    }
}

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?