How to connect visual basic 2008 to sql server 2008? - sql-server-2008

Can anyone please guide me on how to connect Visual Basic 2008 to an SQL server 2008 database? I'm confused on what is the best practice when it comes to this.

There are many many ways. However this is the one of the simplest just using the .net libraries.
you connect to the DB using the server, db and user names and password
you issue a sql command
you collect the results in a sqldatareader
you iterate over the results in the reader
you clean up the the resources.
From: How to ADO.NET SqlDataReader
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sql As String
' Use this first connection string if using windows auth
' connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True"
connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here , like Select * from product"
sqlCnn = New SqlConnection(connectionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " - " & sqlReader.Item(2))
End While
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

From MSDN : Connecting to Microsoft SQL Server 2008 from Microsoft Visual Studio 2005 and 2008

Related

Cannot connect to remote database using mySQL on a form in VB.net

Trying to connect to a remote database on my hostinger.de account using VB.net. Connecting to the database using PHP on my hostinger.de website works just fine. Trying to connect via VB.net from desktop throws an error message:
a network-related error occurred... Win32Exception: The network path was not found."
I double-checked the server path. It is exactly as mentioned in my php admin area. Connecting via MySQL workbench works fine.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim myReader As SqlDataReader
Dim results As String
myConn = New SqlConnection("server=sql588.main-hosting.eu;uid=u942496093_User1;database=u942496093_Test1;password=abcDEF123!")
'myConn = New SqlConnection("server=145.14.151.51;uid=u942496093_User1;database=u942496093_Test1;password=abcDEF123!")
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT Vorname, Nachname FROM TestTabelle1"
myConn.Open()
myReader = myCmd.ExecuteReader
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
MsgBox(results)
myReader.Close()
myConn.Close()
End Sub
End Class

What is the ConnectionString to connect MySQL db with VB.NET

I am working on to connect my App form VB.Net with MySQL table database with this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
Dim con As New SqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag='" & Rfid_tagTextBox.Text & "'"
Dim cm As New SqlCommand(com, con)
Dim rd As SqlDataReader = cm.ExecuteReader()
If rd.Read() = True Then
MessageBox.Show("Valid username and password")
Else
MessageBox.Show("Invalid username and password", caption:="login")
End If
End Sub
But when I run the app gave me this error:
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name
is correct and that SQL Server is configured to allow remote
connections. (provider: Named Pipes Provider, error: 40 - Could not
open a connection to SQL Server)
What is the correct ConnectionString to use with MySQL 5.7.
The connection string below is an SQL Server connection string:
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
According to MySQL Connector .NET connection string, you should provide server name, port number (if using different port), database name and credentials like this:
Dim str As String = "Server=localhost;Port=3306;Database=tabledb;Uid=root;Pwd=password1234"
Also you should use MySqlConnection, MySqlCommand & MySqlDataReader instances with parameters instead of value concatenation inside query string (ensure that reference to MySql.Data.dll added first):
Using con As New MySqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag=#tag"
Using cm As New MySqlCommand(com, con)
cm.Parameters.Add("#tag", MySqlDbType.VarChar).Value = Rfid_tagTextBox.Text
Dim rd As MySqlDataReader = cm.ExecuteReader()
' Check if any rows exist
If rd.HasRows = True Then
' do something
Else
' do something else
End If
End Using
End Using

vb.net cannot connect to sql server

I am trying to make a login database using vb.net. I am using this code to connect but it doesn't work!:
Public Class Form1
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=localhost; Initial Catalog=user; Integrated Security= true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from auth where login= '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
Welcome.Show()
Else
MessageBox.Show("Login Failed", "error")
End If
End Sub
End Class
I have a data base on my sql server called "user" and in user there is a table named "dbo.auth". When I click Label2, visual basic says "con cannot be opened" I am using MySQL server workbench. Is there any way I can fix this? The server is also running on my local network.
Does this work for you?
Imports System.Data.SqlClient
Public Class LoginForm1
Dim conn As SqlConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
conn = New SqlConnection
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Try
conn.Open()
MsgBox("Connected!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Also, I think you should bookmark the link below.
https://www.connectionstrings.com/

How to fix web connection failed to load data from my database

Im trying to create a simple database load connection through web page but it always give me an error: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
This is my web.config, using MySQL, MySQL server 2005
<connectionStrings>
<add name="MySQLConnection" connectionString="database=peronrecords;server=localhost;uid=root;pwd=root"/>
</connectionStrings>
And this is my vb code using gridview:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MySQLConnection").ToString())
' Create a DataSet object.
Dim da As SqlDataAdapter
Dim dt As New DataTable
da = New SqlDataAdapter("SELECT id, name FROM student", conn)
da.Fill(dt)
' Open the connection
conn.Open()
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Sub
If you are connecting to MySql then you need to use the appropriate classes.
The SqlConnection and SqlDataAdapter are the classes required to connect to Microsoft Sql Server, for MySql you need the MySqlConnection and MySqlDataAdapter.
These classes could be found if you download and install the MySql NET Connector, then add a reference to MySql.Data.dll and add an Imports statement for MySql.Data.MySqlClient to the top of your code file.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Using conn As New MySqlConnection(ConfigurationManager.ConnectionStrings("MySQLConnection").ToString())
' Create a DataSet object'
Dim da As MySqlDataAdapter
Dim dt As New DataTable
da = New MySqlDataAdapter("SELECT id, name FROM student", conn)
da.Fill(dt)
' Not needed. The DataAdapter opens the connection by itself if it is not opened
' conn.Open()
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Sub

SQL and VISUAL BASIC 2008 Queries

How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.