SyntaxHighlighter

ラベル C# の投稿を表示しています。 すべての投稿を表示
ラベル C# の投稿を表示しています。 すべての投稿を表示

2021-12-23

[C#][Windows] MessageBox中に改行処理

仕事メモです。

Windowsプログラミングによく使用するMessageBox。大量の内容を見せやすくするには改行が必要不可欠です。

いちいちCrLfを追加するのが面倒くさいので、より分かりやすくなる名前はC#内にあるようです。

Environment.NewLine

上記の意味ある内部変数を使ったらいいです。将来LinuxやMacに変更しても同じもので対応可能。通常のCrLfはWindowsのみであり、OSによる覚え間違いは減りますが、長い英単語を覚える方が逆に難しい…なんです。

2021-10-03

LeetCode 01: Two Sum

 長い間ウワサは聞いておりますが、初めて触りました。リートコード(LeetCode)という中国発のネットジャージシステム。一応自分が登録したのはアメリカサーバですけどね。

多分アルゴリズム上ではそこまで最適化していませんが、一応コードを記録しておくことに:


public class Solution {
    public int[] TwoSum(int[] nums, int target) {
            int index1=0;
            int index2=1;

            int maxindex = nums.Length;

            while (true)
            {
                int solution = nums[index1] + nums[index2];
                if (solution == target)
                {
                    int[] result = new int[] { index1, index2 };
                    return result;
                }

                index2++;

                if(index2 >= maxindex)
                {
                    index1++;
                    index2 = index1 + 1;
                }
            }
    }
}
            

2021-09-13

在多個專案中同時設定依賴專案版本

如果你像我在做Blazor的披薩工作坊時,執行build卻發生像下面的錯誤:

warning NU1604: Project dependency 'PackageA' (<= 9.0.0) does not contain an inclusive lower bound. Include a lower bound in the dependency version to ensure consistent restore results.

很好,第一步你找對地方了。這是一個msbuild的問題,也是這個工作坊內容的一個小問題。
這個專案中牽扯到了nuget包裝版本問題。而通常我們在github等上傳資料時,並不會包含nuget引用的封包(可以自己抓的就不要浪費網路流量啦)。

基本上專案用的方法並沒有錯,他只是少傳了一個檔案。在這個檔案中,我們可以將多個proj所需的最低版本放到同一個檔案中集中管理,這樣升級的時候就不需要一個一個去打開專案檔修改參考版本。

你所需要做的動作如下:
1. 在Solution檔案夾下放一個共通的檔案。如果你像我常常使用VSCode,那就是把檔案放在sln檔的同一個目錄中。在標準設定中,他會被叫做Directory.Build.props
2. 修改檔案內容,改成像下面這樣:
<Project>
<PropertyGroup Label="Package Dependencies">
<AspNetCoreVersion>5.0</AspNetCoreVersion>
<EntityFrameworkVersion>5.0</EntityFrameworkVersion>
<BlazorVersion>5.0</BlazorVersion>
<SystemNetHttpJsonVersion>5.0</SystemNetHttpJsonVersion>
</PropertyGroup>
</Project>
3. 如果你是用dotnet cli或是Visual Studio,恭喜你,你已經可以正常build了。
如果你不是使用標準build。那你就繼續做下一步。
4. 打開你的各個專案檔(就是那些csproj檔)。在<Project>的最上層添加下面這行
<import Project="..\Directory.Build.props" />
5. 結束。這樣應該又恢復正常了。未來有升級的時候,自己進去修改所需最低nuget的版本,看是要改成6.0還是什麼的,就看大家造詣了。

ref: https://github.com/dotnet-presentations/blazor-workshop

keyword: asp.net, dependencies.props, Directory.Build.props, .net core

2021-02-12

DataGridCheckBoxColumn動作模式變更

DataGridCheckBoxColumn裡的CheckBox,在預設狀態下,必須先點一次,Row取得focurs之後才能改變狀態。使用上不是很直覺,跟一般的CheckBox不太一樣。

背後的原因是因為DataGridCell本身有分成顯示用的ElementStyle跟編輯用的EditElementStyle兩種模式,為了做出區分,犧牲了CheckBox的直覺性。

可以依靠設定Style的方法,使操作更為直覺。

修改方式如下:

在各自的Style設定中(可以放在上位DataGrid的DataGrid.Resource裡),加入以下程式碼
<Style TargetType="CheckBox" x:Key="CheckBoxCellStyle" />

或是
<Style TargetType="CheckBox" x:Key="CellCheckBoxStyle"
       BasedOn="{StaticResource {x:Type CheckBox}}" />

然後就可以在DataGridCheckBoxColumn上設定我們所需的ElementStyle
<DataGridCheckBoxColumn Binding="{Binding Selected}"
                        ElementStyle="{StaticResource CheckBoxCellStyle}" />

做完以上的設定,指定的DataGridCheckBoxColumn裡面的CheckBox就會是我們常用的單點就會有反應的CheckBox了。

以上。

2020-09-28

PrismでDIコンテナを使用するRegister vs RegisterInstance vs RegisterSingleton

Prism 7以降に、サービスを注入する際に、Register, RegisterSingleton, RegisterInstance三つのメソッドが使えます。それぞれを使用する場面について、ちょっとした解説を書き残します。

実際にサービスを登録する場合、そのサービスを使用する場面によって、異なるサービスを使用するべきと言われていますが、次のように大まかに分けています:

  • Register 該当Interfaceが注入された場合、DIコンテナが自動的に新しいインスタンスを生成し、終わったときにインスタンスを廃棄する。
  • RegisterSingleton 全部の注入には同じインスタンスで対応する。
  • RegisterInstance 主にRegisterSingletonと同じだが、生成されるInstanceは自分で管理する場合使用。

では、どれを使うほうか正解ですか?

まぁ、ほとんどなサービスはSingletonとして登録されます。ViewModelはそれらのサービスによって通信できるようにするためです。例えば、EventAggregatorサービスで、あなたが持つあるViewModelからEventを発行する際に、他の何かはそのことを知らせたいですが、それは同じインスタンスのサブスクリプションを発行者サービスとして登録している場合受け取ることができます。とはいえ、WCFクライアントは、同じシングルトンを使用する必要はありません。なぜならば、その処理はサーバー側が処理すべきなのです。

場合によっては、インスタンスを登録することは嫌がります。特に登録(register)と逆解析(resolve)が混在している場合。インスタンスを作成する際にそのインスタンスの依頼先をすべて確保する場合も。(だからResolveを呼び出す。その呼び出す自体がやや気に障るが。)

ひとつのメソッドですべての必要項目を全部登録してしまえば問題は減りますが、複数の交互依頼モジュールがある場合にはちょっと頭痛いです。

訳者注記

最近のプロジェクトでDBのアクセスサービスに、Singletonの登録にはちょっと問題あると気付きました。EntityFrameworkのDbContextを利用していますが、すべての画面が同じDbContextを登録した場合、DB側に更新がある場合、リアルタイムにReloadができません。渋々にSingletonを解除して、画面ごとに新しいDbContextを使うことにしたら、キレイに解決しました。ネットで検索したら、DbContextは長時間メモリに滞在するようには良い影響はしないようです。とりあえずEntityFrameworkのDbContextはSingleton登録しないようにする方が良いです。あるいは必要の場合自分でインスタンスを管理する方が良いかもしれません。

2019-12-09

WPFでEFオブジェクトにData Bindingする場合の4t自動設定

WPFコントロールに自動的にBindingする場合、
デフォルトの4Tフレームワークで生成するファイルに少しだけの変更を入れると、あとはいつもの通りに任せきりにします。

内容はMSDNの公式文書からの抜粋で、私なりに必要な部分だけ取り出しました。

まず、適用する環境は次の通り:

  • Visual Studio Express 2017 for Windows Desktop
  • SQL Server Express 2017(大事でないけど、一応記録しておく。)
  • EF 6.0
  • WPF 3.0以上
そして、使用する手法はDatabase Firstで、ある程度データベースに保存するデータの形はDBですでに定義している前提で進みます。

ちなみに、MSDN公式は次の通り
MSDN公式を閲覧した時点では内容めちゃくちゃなので、蛇足ですが私なりに訳しておきました。
https://hackmd.io/@rokashou/rkSHqVM2H

カギになる設定の部分を抜粋:

  • ソリューションエクスプローラーを開き、edmxファイルの下にあるttファイル探します。編集としてファイルを開けます。
  • 二箇所にある「ICollection」を「ObservableCollection」へ置き換えます。それぞれは約296行目と484行目あたりにあります。
  • 最初に出た「HashSet」を見つけて「ObservableCollection」に置き換えます。 それは約50行目にあります。コードの後半にある2番目のHashSetを置き換えないでください
  • 一回だけある「System.Collections.Generic」を検索し、「System.Collections.ObjectModel」に置き換えます。 それは約424行目にあります。
  • .ttファイルを保存します。 これにより、エンティティのコードが再生成されます。 コードが自動的に再生成されない場合は、.ttファイルを右クリックして、「カスタムツールの実行」を選択します。

以上。

あとは普通にプログラムを組んでください。
ちょっと前のやつにはいろいろ不具合があるようで、見つけた次第にエラーでないように更新していく…



2013-10-28

[C#]Centering a Message Box on the Active Window

There are 2 way to centering the default MessageBox
or said, 1 only way, and 2 kind of Invoking.

1. Make a new WindowForm who has centerParent Location, then copy it's location to the MessageBox by "Hook" the system dialog's location.
2. Just Hook the system dialog's location and set it before call MessageBox.Show()

Way 1: CenterWinDialog by Hans Passant

There's the code(class CenterWinDialog):
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CenterWinDialog : IDisposable {
    private int mTries = 0;
    private Form mOwner;

    public CenterWinDialog(Form owner) {
        mOwner = owner;
        owner.BeginInvoke(new MethodInvoker(findDialog));
    }

    private void findDialog() {
        // Enumerate windows to find the message box
        if (mTries < 0) return;
        EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
        if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) {
            if (++mTries < 10) mOwner.BeginInvoke(new MethodInvoker(findDialog));
        }
    }
    private bool checkWindow(IntPtr hWnd, IntPtr lp) {
        // Checks if <hwnd> is a dialog
        StringBuilder sb = new StringBuilder(260);
        GetClassName(hWnd, sb, sb.Capacity);
        if (sb.ToString() != "#32770") return true;
        // Got it
        Rectangle frmRect = new Rectangle(mOwner.Location, mOwner.Size);
        RECT dlgRect;
        GetWindowRect(hWnd, out dlgRect);
        MoveWindow(hWnd,
            frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) / 2,
            frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) / 2,
            dlgRect.Right - dlgRect.Left,
            dlgRect.Bottom - dlgRect.Top, true);
        return false;
    }
    public void Dispose() {
        mTries = -1;
    }

    // P/Invoke declarations
    private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
    [DllImport("user32.dll")]
    private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentThreadId();
    [DllImport("user32.dll")]
    private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
    [DllImport("user32.dll")]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int w, int h, bool repaint);
    private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
}

Usage:
    private void button1_Click(object sender, EventArgs e) {
        using (new CenterWinDialog(this)) {
            MessageBox.Show("Nobugz waz here");
        }
    }


Way 2: MessageBoxHelper by Jason Carr

There's the code(class MessageBoxHelper):
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal static class MessageBoxHelper
{
    internal static void PrepToCenterMessageBoxOnForm(Form form)
    {
        MessageBoxCenterHelper helper = new MessageBoxCenterHelper();
        helper.Prep(form);
    }

    private class MessageBoxCenterHelper
    {
        private int messageHook;
        private IntPtr parentFormHandle;

        public void Prep(Form form)
        {
            NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
            GCHandle.Alloc(callBackDelegate);

            parentFormHandle = form.Handle;
            messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
        }

        private int CenterMessageCallBack(int message, int wParam, int lParam)
        {
            NativeMethods.RECT formRect;
            NativeMethods.RECT messageBoxRect;
            int xPos;
            int yPos;

            if (message == 5)
            {
                NativeMethods.GetWindowRect(parentFormHandle, out formRect);
                NativeMethods.GetWindowRect(new IntPtr(wParam), out messageBoxRect);

                xPos = (int)((formRect.Left + (formRect.Right - formRect.Left) / 2) - ((messageBoxRect.Right - messageBoxRect.Left) / 2));
                yPos = (int)((formRect.Top + (formRect.Bottom - formRect.Top) / 2) - ((messageBoxRect.Bottom - messageBoxRect.Top) / 2));

                NativeMethods.SetWindowPos(wParam, 0, xPos, yPos, 0, 0, 0x1 | 0x4 | 0x10);
                NativeMethods.UnhookWindowsHookEx(messageHook);
            }

            return 0;
        }
    }

    private static class NativeMethods
    {
        internal struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        internal delegate int CenterMessageCallBackDelegate(int message, int wParam, int lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool UnhookWindowsHookEx(int hhk);

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("kernel32.dll")]
        internal static extern int GetCurrentThreadId();

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern IntPtr SetWindowsHookEx(int hook, CenterMessageCallBackDelegate callback, IntPtr hMod, int dwThreadId);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    }
}


Usage:
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBoxHelper.PrepToCenterMessageBoxOnForm(this);
        MessageBox.Show("Hello!", "Hello!", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0);
    }

2013-10-25

[C#]Force DataGridView Save Current Row's Data to Backyard.

Usually we edit the table data with DataGridView.

I do it, too. and I get problem when I try to get the changed DataTable.

It happened if you try to save data just after editing it.


There is the situation:

I have a 3x3 DataTable dt, and I link it to a DataGridView dgv
dgv.DataSource = dt;

then I edited the content with row 3 column 3.
I can move cursor to column 1 or column 2, but before i move cursor to the other row, the changing of row 3 will not be set to DataTable.

It's not good. I want it be saved after click SAVE or Ctrl-S.

So, there is a solution: DataGridView.EndEdit().
but, the row's data didn't change with only DataGridView.EndEdit().
The CurrentRow must lose focus to save the data.
Hmm... Here is a member called CurrentCell
and Someone set CurrentCell to null, then the data is stored.

I tried it, and it works good!
so, if you want to save the current row's data.
run the below 2 statement:

dgv.EndEdit();
dgv.CurrentCell = null;

then the current row's change will be saved in to DataTable, too.


[C#]Get DataTable from Database, Update DataTable to Database

just take a note.

When we want to update database with a list, as you know, there will be 3 kinds of operation: insert(for new rows), update(for changed rows), delete(for deleted rows)

for a single record, it will be easy. But for a list of data, it will be a nightmare.

use the .NET DataAdapter, we can make it easier.
for base, we have sqlConnectString for default connection, and we try to access all columns of demoTable. There is a global DataTable named dt.

to make the example for common case, I will type it for SQL server.

1. to get DataTable from Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    using(var cmd = new SQLCommand(conn))
    {
        cmd.CommandText = sql;
        var reader = cmd.ExecuteReader();
        dt.Load(reader);
    }
}
2. to update DataTable's data to Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    var adp = new SQLDataAdapter(sql, conn);
    var cmb = new SQLCommandBuilder(adp);
    adp.Update(dt);
}

to speed up the database access, can add transaction commands. Begin the transaction before update, and commit the transaction after update.

2013-06-05

Call Win32 DLL from C#

參考網址:

Win32 APIやDLL関数を呼び出すには? - http://www.atmarkit.co.jp/fdotnet/dotnettips/024w32api/w32api.html

C# Win32 API および DLL の利用
http://typea.info/tips/wiki.cgi?page=C%23+Win32+API+%A4%AA%A4%E8%A4%D3+DLL+%A4%CE%CD%F8%CD%D1

[C#] 使用 Win32 API 來進行控制其他程式視窗行為表現
http://www.dotblogs.com.tw/nobel12/archive/2009/10/05/10915.aspx

(筆記) 如何使用C#使用Win32 DLL? (.NET) (C#) (Windows Form)
http://www.cnblogs.com/oomusou/archive/2011/02/13/cs_pinvoke.html

2013-06-04

ASCII String/Char to Byte

String -> Byte

string sTest = "TEST"
byte[] bTest = Encoding.ASCII.GetBytes(sTest);


Char -> Byte

Char cTest = 'A'
byte bTest = Convert.toByte(cTest);


Convert BitArray to Byte

byte ConvertToByte(BitArray bits) 
{
	if (bits.Count != 8) { throw new ArgumentException("bits"); }     
	byte[] bytes = new byte[1];     
	bits.CopyTo(bytes, 0);     
	return bytes[0]; 
}

[C#]string,char,byteの相互変換


文字を表現する各種データ型の変換方法です。
Stringから他の型に変換する場合は、文字コードの指定が必要となります。

string -> char

string str = "hello world";
 
//文字列をcharの配列に変換する
char[] charArray = str.ToCharArray();
 
//文字列を、1文字づつcharとして処理する
foreach (char c in str) {
    Console.WriteLine( c );
}
 
//文字列のn文字目をcharとして取得する
int n = 5;
char c = str[n];


char -> string

char c = "あ";
string s = c.ToString();


string -> byte

byte[] bytesArray = xxx;
 
// SJISのbyte配列をstringに変換
str = System.Text.Encoding.GetEncoding( 932 ).GetString( bytesArray );
 
// UTF-8のbyte配列をstringに変換
str = System.Text.Encoding.UTF8.GetString( bytesArray );



byte -> string

string str = "hello world";
byte[] bytesArray;
 
// stringをSJISのbyte配列に変換
byte[] bytesArray = System.Text.Encoding.GetEncoding( 932 ).GetBytes( str );
 
// stringをUTF-8のbyte配列に変換
byte[] bytesArray = System.Text.Encoding.UTF8.GetBytes( str );



byte -> char

byte[] bytesArray = ...;
char[] charArray  = System.Text.Encoding.GetEncoding( 932 ).GetString( bytesArray ).ToCharArray();



char -> byte

char c = "あ";
byte b = Convert.ToByte( c );

2013-04-05

Connect to Databases in C#

今回はC#でSQLiteやMySQLに繋ぎ方法を記録する。

一言で言うと、SQL Serverとの繋ぎはほぼ似ている。
ただし使用するメソッド/オブジェクトをSqlXxxからSQLiteXxxあるいはMySqlXxxに変わるだけ。

さて、本題に入る。先ずは基本のSQL serverに行こう。
することは全部同じ。

  1. データベースに繋ぎ(連結する)。
  2. CarというTableを作成。
  3. テーブルCarにデータを入れる。
  4. データを出力し、連結をクローズする。

using System;
using System.Data.SqlClient;

class SQLTest01
{
    static void Main()
    {
        /* Set the connection string
         * With the setting below:
         * user id : the userid for SQL server
         * password or pwd : the password of user
         * database : the database you want to connect
         */
        string cs = "user id=testuser;" +
            "password=testpwd;server=localhost;" +
            "Trusted_Connection=yes;" +
            "database=dbTest; " +
            "connection timeout=30";

        // Connection to Database
        // with the new "using" garbage collection 
        using (SqlConnection con = new SqlConnection(cs))
        {
            // Open connection;
            con.Open();

            // Create the Table
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = con;

                cmd.CommandText = "DROP TABLE IF EXISTS Cars";
                cmd.ExecuteNonQuery();
                cmd.CommandText = @"CREATE TABLE Cars(Id INTEGER PRIMARY KEY, 
                    Name TEXT, Price INT)";
                cmd.ExecuteNonQuery();
            }

            // Put Datas into Table
            using(SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = con;

                // do with Prepare();
                cmd.CommandText = "INSERT INTO Cars(Id, Name, Price) VALUES(@Id, @Name, @Price)";
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@Id", 1);
                cmd.Parameters.AddWithValue("@Name", "Audi");
                cmd.Parameters.AddWithValue("@Price", 52642);
                cmd.ExecuteNonQuery();
                cmd.Parameters.AddWithValue("@Id", 2);
                cmd.Parameters.AddWithValue("@Name", "Mercedes");
                cmd.Parameters.AddWithValue("@Price", 57127);
                cmd.ExecuteNonQuery();

                // do with Standard SQL command
                cmd.CommandText = "INSERT INTO Cars VALUES(3,'Skoda',9000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(4,'Volvo',29000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(5,'Bentley',350000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(6,'Citroen',21000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(7,'Hummer',41400)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(8,'Volkswagen',21600)";
                cmd.ExecuteNonQuery();
            }

            // Read Datas with DataReader
            string stm = "SELECT * FROM Cars LIMIT 5";
            using (SqlCommand cmd = new SqlCommand(stm,con))
            {
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        Console.WriteLine(rdr.GetInt32(0) + " " + rdr.GetString(1) + " " + rdr.GetInt32(2));
                    }
                }
            }

            // Close connection;
            con.Close();
        }
    }
}



続き、似ている内容で、SQLiteでしましょう。
注意してほしい点は

  • 事前にSystem.Data.SQLiteのDLLファイルをプロジェクトのフォルダ下のExternalsにコピーしておくこと。また、プロジェクト設定でそれに参照するように設定して下さい。
  • DLLファイルを持っていない場合、SQLite.NET公式サイトあるいはSQLite公式サイトより探して下さい。無償で手に入れるはず。

using System;
using System.Data.SQLite;

class SQLTest01
{
    static void Main()
    {
        /* Set the connection string
         * With the setting below:
         * user id : the userid for SQL server
         * password or pwd : the password of user
         * database : the database you want to connect
         */
        string cs = "URI=file:test.db";

        // Connection to Database
        // with the new "using" garbage collection 
        using (SQLiteConnection con = new SQLiteConnection(cs))
        {
            // Open connection;
            con.Open();

            // Create the Table
            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                cmd.Connection = con;

                cmd.CommandText = "DROP TABLE IF EXISTS Cars";
                cmd.ExecuteNonQuery();
                cmd.CommandText = @"CREATE TABLE Cars(Id INTEGER PRIMARY KEY, 
                    Name TEXT, Price INT)";
                cmd.ExecuteNonQuery();
            }

            // Put Datas into Table
            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                cmd.Connection = con;

                // do with Prepare();
                cmd.CommandText = "INSERT INTO Cars(Id, Name, Price) VALUES(@Id, @Name, @Price)";
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@Id", 1);
                cmd.Parameters.AddWithValue("@Name", "Audi");
                cmd.Parameters.AddWithValue("@Price", 52642);
                cmd.ExecuteNonQuery();
                cmd.Parameters.AddWithValue("@Id", 2);
                cmd.Parameters.AddWithValue("@Name", "Mercedes");
                cmd.Parameters.AddWithValue("@Price", 57127);
                cmd.ExecuteNonQuery();

                // do with Standard SQL command
                cmd.CommandText = "INSERT INTO Cars VALUES(3,'Skoda',9000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(4,'Volvo',29000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(5,'Bentley',350000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(6,'Citroen',21000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(7,'Hummer',41400)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(8,'Volkswagen',21600)";
                cmd.ExecuteNonQuery();
            }

            // Read Datas with DataReader
            string stm = "SELECT * FROM Cars LIMIT 5";
            using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
            {
                using (SQLiteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        Console.WriteLine(rdr.GetInt32(0) + " " + rdr.GetString(1) + " " + rdr.GetInt32(2));
                    }
                }
            }

            // Close connection;
            con.Close();
        }

        Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine();
    }
}



最後、MySQL(今回はローカルを例にする)でしましょう。
SQLiteの時と同じ、System.Data.MySQLのDLLを取得して下さい。SQLiteの時と同じ、MySQLの公式サイトより無償で手に入れるはず。


using System;
using MySql.Data.MySqlClient;

class SQLTest01
{
    static void Main()
    {
        /* Set the connection string
         * With the setting below:
         * user id : the userid for SQL server
         * password or pwd : the password of user
         * database : the database you want to connect
         */
        string cs = "user id=testuser;" +
            "password=testpwd;server=localhost;" +
            "database=testDB; " +
            "connection timeout=30";

        // Connection to Database
        // with the new "using" garbage collection 
        using (MySqlConnection con = new MySqlConnection(cs))
        {
            // Open connection;
            con.Open();

            // Create the Table
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = con;

                cmd.CommandText = "DROP TABLE IF EXISTS Cars";
                cmd.ExecuteNonQuery();
                cmd.CommandText = @"CREATE TABLE Cars(Id INTEGER PRIMARY KEY, 
                    Name TEXT, Price INT)";
                cmd.ExecuteNonQuery();
            }

            // Put Datas into Table
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = con;

                // do with Prepare();
                cmd.CommandText = "INSERT INTO Cars(Id, Name, Price) VALUES(1, 'Audi', 52642)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars(Id, Name, Price) VALUES(2, 'Mercedes', 57127)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(3,'Skoda',9000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(4,'Volvo',29000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(5,'Bentley',350000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(6,'Citroen',21000)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(7,'Hummer',41400)";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "INSERT INTO Cars VALUES(8,'Volkswagen',21600)";
                cmd.ExecuteNonQuery();
            }

            // Read Datas with DataReader
            string stm = "SELECT * FROM Cars LIMIT 5";
            using (MySqlCommand cmd = new MySqlCommand(stm, con))
            {
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        Console.WriteLine(rdr.GetInt32(0) + " " + rdr.GetString(1) + " " + rdr.GetInt32(2));
                    }
                }
            }

            // Close connection;
            con.Close();
        }
    }
}

人気の投稿