VisualBasic2008上で作ったデータベースにアクセスしてみる。



ボタン1 接続の試験

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim cn As New System.Data.SqlServerCe.SqlCeConnection

Try
cn.ConnectionString = "Data Source=D:\databaseApplication1\Database1.sdf;"
cn.Open()
TextBox1.Text = "Connection sucsess"

Catch ex As Exception
TextBox1.Text = ex.Message

Finally
cn.Close()
End Try

End Sub



ボタン2 データベースから読み込む

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim cn As New System.Data.SqlServerCe.SqlCeConnection
Dim cmd As System.Data.SqlServerCe.SqlCeCommand
Dim dread As System.Data.SqlServerCe.SqlCeDataReader

Try
'SQLサーバへ接続
cn.ConnectionString = "Data Source=D:\databaseApplication1\Database1.sdf;"
cn.Open()
Me.TextBox1.Text = "Connection sucsess"

'SQLコマンドの設定
cmd = New System.Data.SqlServerCe.SqlCeCommand("SELECT * FROM CustomerInfo", cn)
'データの読み込みSQLの実行
dread = cmd.ExecuteReader()

'出てきたデータを順に読み出す
Do While (dread.Read())
'データをリストボックスへ表示
Me.ListBox1.Items.Add(dread.GetInt32(0) & ControlChars.Tab & dread.GetString(1) & ControlChars.Tab & dread.GetString(2) & ControlChars.Tab & dread.GetString(3))

Loop
dread.Close()

Catch ex As Exception
'エラー表示
TextBox1.Text = ex.Message

Finally

cn.Close()
End Try

End Sub


09/10/30 17:06:32