Archive for 9月, 2012
VisualStudio2010でSQLServer2000へ接続
by achi on Sep.10, 2012, under VB.NETテクニック, プログラム
VS2010では悲しいことにデータベースエクスプローラではSQL2000がサポートされない。
どっこらしょ、っと二種類のDB、テーブルへ接続してレコードを取得、DataGridViewへ放り込んだソース。
備忘録として記録。
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If RadioButton2.Checked Then
Dim connectionStr As String
Dim sqlStr As String
Dim dtsrc As New DataTable
Dim nsda As SqlDataAdapter
Try
‘接続
connectionStr = “Server=ServerAddress;Initial Catalog=DB_Name;User ID=User;Password=password”
Dim tnc1 As String = “”
Dim tnc2 As String = “”
Dim tnc3 As String = “”
Dim tnc4 As String = “”
Dim dbname As String = “”
Select Case ComboBox1.Text
Case anyting
dbname = “dbname”
End Select
sqlStr = “Select * From ” & dbname & ” ”
If TextBox1.Text <> “” Then
tnc1 = TextBox1.Text
sqlStr = sqlStr & ” Where nou_tcd = ” & tnc1 & “”
End If
If TextBox2.Text <> “” Then
tnc2 = TextBox2.Text
sqlStr = sqlStr & ” or nou_tcd = ” & tnc2 & “”
End If
If TextBox3.Text <> “” Then
tnc3 = TextBox3.Text
sqlStr = sqlStr & ” or nou_tcd = ” & tnc3 & “”
End If
If TextBox4.Text <> “” Then
tnc4 = TextBox4.Text
sqlStr = sqlStr & ” or nou_tcd = ” & tnc4 & “”
End If
‘コネクション生成
Using con = New SqlConnection(connectionStr)
‘接続
con.Open()
‘SqlCommand生成
Dim cmd = New SqlCommand(sqlStr, con)
nsda = New SqlDataAdapter(cmd)
nsda.Fill(dtsrc)
DataGridView1.DataSource = dtsrc
con.Close()
con.Dispose()
End Using
Catch ex As Exception
MsgBox(ex.Message)
Finally
End Try
ElseIf RadioButton1.Checked Then
Dim connectionStr As String
Dim sqlStr As String
Dim dtsrc As New DataTable
Dim nsda As SqlDataAdapter
Try
‘接続
connectionStr = “Server=ServerAddress;Initial Catalog=DB_Name;User ID=User;Password=password”
Dim otherdb As String = “otherdb”
sqlStr = “Select * From ” & otherdb & ” ”
‘コネクション生成
Using con = New SqlConnection(connectionStr)
‘接続
con.Open()
‘SqlCommand生成
Dim cmd = New SqlCommand(sqlStr, con)
nsda = New SqlDataAdapter(cmd)
nsda.Fill(dtsrc)
DataGridView1.DataSource = dtsrc
con.Close()
con.Dispose()
End Using
Catch ex As Exception
MsgBox(ex.Message)
Finally
End Try
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim setcont1 As String = “使い方説明”
Dim setcontal As String
setcontal = setcont1 & vbCrLf
MsgBox(setcontal)
End Sub
End Class