0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【MySQL】VB.net フォームアプリケーションでSQLを操作するクラス(自分用)

Last updated at Posted at 2019-10-28

わざわざモジュールの名前を分けてSQL実行モジュールを呼び出しているのは、
フォームから呼び出した時の可読性を高める為です。

フォームで呼び出す際は、引数にDataGridViewオブジェクトとSQL文を指定します。

Imports MySQL.Data.MySqlClient

Public Class MySqlClass

    Const IP As String = "サーバーのアドレス"
    Const PORTNO As Integer = 3306
    Const USERNAME As String = "ユーザー名"
    Const PASSWORD As String = "パスワード"
    Const DBNAME As String = "データベース名"

    Sub SelectDatagridShow(dataG As DataGridView, StrSQL As String)
        'SELECT文等
        ShowTypeSQL(dataG, StrSQL)
    End Sub

    Sub InsertDB(StrSQL As String)
        'INSERT文
        OperationTypeSQL(StrSQL)
    End Sub

    Sub UpdateDB(StrSQL As String)
        'UPDATE文
        OperationTypeSQL(StrSQL)
    End Sub

    Sub DeleteDB(StrSQL As String)
        'DELETE文
        OperationTypeSQL(StrSQL)
    End Sub

    Sub ShowTypeSQL(dataG As DataGridView, StrSQL As String)
        'DataGridViewに表示する時はこのモジュールを使う
        Dim Builder = New MySqlConnectionStringBuilder()

        With Builder
            .Server = IP
            .Port = PORTNO
            .UserID = USERNAME
            .Password = PASSWORD
            .Database = DBNAME
        End With

        Dim ConStr = Builder.ToString()
        Dim Con As New MySqlConnection

        Con.ConnectionString = ConStr
        Con.Open()

        Dim SqlStr = StrSQL
        Dim Adapter = New MySqlDataAdapter(SqlStr, Con)
        ' データを取得
        Dim Ds As New DataSet
        Adapter.Fill(Ds)
        dataG.DataSource = Ds.Tables(0)
        Con.Close()
    End Sub

    Sub OperationTypeSQL(StrSQL As String)
        'DataGridViewに表示しない時はこのモジュールを使う
        Dim Builder = New MySqlConnectionStringBuilder()

        With Builder
            .Server = IP
            .Port = PORTNO
            .UserID = USERNAME
            .Password = PASSWORD
            .Database = DBNAME
        End With

        Dim ConStr = Builder.ToString()
        Dim Con As New MySqlConnection

        Con.ConnectionString = ConStr
        Con.Open()

        Dim SqlStr = StrSQL
        Dim Adapter = New MySqlDataAdapter(SqlStr, Con)
        Dim Ds As New DataSet
        Adapter.Fill(Ds)
        Con.Close()
    End Sub

End Class

このクラスは今後使いながらアレンジしていきたいなと思います。

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?