Reputation: 1
Win 11 vers: 10.0.22621
VS 2022 vers: 17.7.4
Net. 4.8.0902
SQL Server vers: 15.0.2101.7
Both VS and SQL are on the same pc.
I'm an old vb programmer and a cannot figure out how to connect to SQL Server via: 'Dim cn as New SqlConnection' The intellisense does not list the connection object. Can you please point me to some instructions on how to resolve this? Thank you for your time.
Poked around the internet but could not find any solutions.
Upvotes: 0
Views: 168
Reputation: 5403
If you start a new .NET Framework 4.8 Console App, the following code should work. Replace MyDatabaseName
with the name of your database and MyTableName
with the name of your table.
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString = "Data Source=(local);Timeout=10;Database=MyDatabaseName;Integrated Security=True;"
Dim strSql As String = "SELECT * FROM MyTableName"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
Dim firstRow = dtb.Rows(0)
For col = 0 To dtb.Columns.Count - 1
Dim columnName = dtb.Columns(col).ColumnName
Dim columnValue = CStr(firstRow(columnName))
Console.WriteLine($"{columnName}={columnValue}")
Next col
End Sub
End Module
Upvotes: 0