VB.net + PostgreSQL + Npgsql DBConnect Update Delete Sample

更新または削除のサンプル

Imports Npgsql '忘れずに

     '接続文字列は適当に変更してください。
        Dim builder As New Npgsql.NpgsqlConnectionStringBuilder
        With builder
            .Host = "192.xxx.xxx.xxx"
            .Database = "dbname"
            .Username = "username"
            .Password = "password"
            .Port = 5432
            .Timeout = 20
        End With

        Dim command As NpgsqlCommand = New NpgsqlCommand("insert into tablename(name) values('memo')", conn)

        Dim retcnt = command.ExecuteNonQuery()
        MessageBox.Show("count = " + CStr(retcnt))

     'パラメータ
        '        command.CommandText = "INSERT INTO tablename (memo) VALUES (@p1)";
        '        command.Parameters.AddWithValue("p1", "Hello");

        '        Dim sResult As String = command.ExecuteScalar()

        MessageBox.Show("追加できました")
        conn.Close()

Continue Reading

VB.net + PostgreSQL + Npgsql DBConnect SELECT Sample

ネット上ではC#でのやり方が多かったのでVB.net版で載せます。

Imports Npgsql '忘れずに

     '接続文字列は適当に変更してください。
        Dim builder As New Npgsql.NpgsqlConnectionStringBuilder
        With builder
            .Host = "192.xxx.xxx.xxx"
            .Database = "dbname"
            .Username = "username"
            .Password = "password"
            .Port = 5432
            .Timeout = 20
        End With

        Dim conn As NpgsqlConnection = New NpgsqlConnection(builder.ConnectionString)
        conn.Open()

        Dim command As NpgsqlCommand = New NpgsqlCommand("select * from test", conn)
        Dim dr As NpgsqlDataReader
        dr = command.ExecuteReader()

        If dr.HasRows Then
            MessageBox.Show("hasrows is true")
        End If

        While (dr.Read())
            MessageBox.Show(dr(0))
        End While

        conn.Close()

Continue Reading