How do I connect to SQL Server with VB? - sql-server

I'm trying to connect to a SQL server from VB. The SQL server is across the network uses my windows login for authentication.
I can access the server using the following python code:
import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()
This code works fine, returning the first result of the SELECT. However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. I've tried several different connection strings but this is the current code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
Try
conn.Open()
MessageBox.Show("Sweet Success")
''#Insert some code here, woo
Catch ex As Exception
MessageBox.Show("Failed to connect to data source.")
MessageBox.Show(ex.ToString())
Finally
conn.Close()
End Try
End Sub
It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use.
Thanks!
-Wayne

You are using an ODBC DSN as a SqlClient server name. This is not going to work. You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN).
Replace signinspection with the actual name of your SQL Server host. If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\instancename

Check out connectionstrings.com for samples. It looks like in your python example, you are accessing the DB via ODBC.
The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name.

Sure your Server and Database have the same name?
Here you have a link that would allow you to generate a connection string and test it
http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx.

Well, I went ahead and used an ODBC Connection. It appears that that is what I was wanting in the first place.
In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. Following the directions I came up with the following code that seems to work just fine:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
columnCount = reader.GetValues(data)
output = ""
For i As Integer = 0 To columnCount - 1
output = output & " " & data(i).ToString()
Next
Debug.WriteLine(output)
End While
conn.Close()
Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time.
ed. columsCount -> columCount

You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores.
Good success! =)

Related

Using VB6 with ADO to access a MS SQLServer 2019 linked server

Note that both databases are MS SQL Server.
The SELECT works fine and the code doesn't break until it gets to ADODB.Recordset.Update. The SQL account has all of the necessary permissions. The table [NASMSPAINT].[Ignition].[dbo].[booth_Styles] is a linked server. The User account I am using has enough permissions because I am able to UPDATE the table using Python. This is on a secure isolated network so security is of very little concern, this just needs to work using VB6 with ADO. Long story short, this code is part of a large application still using VB6 and rewriting the code in Visual Studio is not an option.
Using ADODB.Recordset.OPEN using adLockOptimistic option, the following error occurs on the ".Update" line of the code:
SQL server error message 16964 - for the optimistic cursor, timestamp columns are required if the update or delete targets are remote.
Using ADODB.Recordset.OPEN using adLockPessimistic option, the following error occurs on the ".Update" line of the code:
SQL Server Error Msg 16963 – You cannot specify scroll locking on a cursor that contains a remote table.
I have found very little information on the internet concerning these errors. I have set the following server option properties on the linked server on the database:
Collation Compatible: TRUE
Data Access:TRUE
RPC:TRUE
RPC Out:TRUE
Use Remote Collation:FALSE
Collation Name:
Connection Timeout:0
Query Timeout:0
Distributor:FALSE
Publisher:FALSE
Subscriber:FALSE
Lazy Schema Validation:FALSE
Enable Promotion of Distributed Transaction:TRUE
VB6 code:
sDBName = "PROVIDER=SQLOLEDB.1;Data Source=192.168.2.70;User ID=xxxx;Password=xxxx;Persist Security Info=False"
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set Conn = New ADODB.Connection
Conn.Open sDBName
Set rs = New ADODB.Recordset
With rs
.Open "SELECT * FROM [NASMSPAINT].[Ignition].[dbo].[booth_Styles] WHERE [Booth] = 'AdPro' ORDER BY [StyleID]", Conn, adOpenDynamic, adLockOptimistic
.MoveFirst
nThisStyle = 1
Do Until .EOF
![Plant_Number] = Style_Data(nThisStyle).PlantStyle
![Style_Number] = Style_Data(nThisStyle).FanucStyle
![Descript] = Style_Data(nThisStyle).StyleDesc
![Robots_Required] = Style_Data(nThisStyle).StyleRobotsReq
.Update
.MoveNext
nThisStyle = nThisStyle + 1
Loop
End With
The code breaks on the .Update line.

how to connect VBScript (Excel) to SQL Server web database (via IP)

I'm at my job trying to do some unknow stuff for me, you see, we're trying to connect an excel document with a VBScript Macro to a databse stored in web server but for some reason doesn't recognizes the user and throws an error repeatedly, i discarded a connection issue since it returns an SQL error instead of something like a timeout or server doesn't exists or something like that, we're trying to connect to the server using the ip address, we also checked that the logging method is on mixed (win and sql) and remotes connections to the server are enabled as well, also if i use the credentials provided in the connection string (username and password) i can actually log in to SQL Server without any issue, we also tried a direct connection (external vpn) because we thought it could be our firewall, but got the same error anyway, so we have no clue what it could be and we're kinda running out of ideas on how to do this, i'll post down below the code i'm using to trying the connection (obviously test data but similar to reality)
picture of the error i'm getting (don't post the original since it's in spanish but is very similar to this):
code i'm currently trying:
Sub excel_sqlsrv()
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
strConn = "Driver={ODBC Driver 17 for SQL Server};Server=10.20.30.5;Database=mydb;UID=sa;PWD=abcd12345;"
conn.Open strConn
strSqL = "SELECT * FROM USERS"
rs.Open strSqL
End Sub
Any advice, tip or trick could be of tremendous help for me, i'll be looking forward to any kind of comment, thanks in advance
Use the ODBC Data Source Administrator to create a connection named mydb and test it works. Then use
Sub excel_sqlsrv()
Const strConn = "mydb" ' ODBC source
Const strsql = "SELECT * FROM USERS"
Dim conn As Object, rs As Object
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open strConn
If conn.Errors.Count > 0 Then
Dim i, s
For i = 0 To conn.Errors.Count - 1
s = s & conn.Errors(i) & vbLf
Next
MsgBox s
Else
On Error GoTo 0
Set rs = conn.Execute(strsql)
Sheet1.Range("A1").CopyFromRecordset rs
End If
End Sub
You can try using OLEDB provider instead of ADODB.

Error connecting to SQL Server 2012 with VB.NET 2010

I have been trying to fix a project which already use a 100% connections to Oracle. They are trying to upgrade the project to start using SQL Server 2012 Management Studio. But I'm having issues connecting to the database. We use Windows authentication.
I can login fine directly to SQL Server 2012 using Management Studio and Windows authentication. If I create a fresh new WindowsApplication1 project to test the connection code it works fine, I'm using this code (and get an error is at conn.Open()):
Imports System.Data.SqlClient
Public Class Open_Filing_Image
'Create ADO.NET objects.
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private results As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Create a Connection object.
Dim connStr As [String] = "Server=servername; Database=dbname; Integrated Security=True"
myConn = New SqlConnection(connStr)
'Create a Command object.
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT DdocName FROM dbo.Document WHERE XAlaskaID = '72010' and DdocType = 'Filings'"
'Open the connection.
Try
myConn.Open()
MsgBox("Connection Open ! ")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
myReader = myCmd.ExecuteReader()
'Concatenate the query result into a string.
Do While myReader.Read()
results = myReader.GetValue(0)
Loop
'Display results.
Dim documentID As String = results
Dim outPath As String = "http://address.internet`enter code here`/" + documentID + (".pdf")
System.Diagnostics.Process.Start(outPath)
'Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
Error message:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The specified data could not be decrypted.
Thank you.
Fix it doing some research and some assistance by another programmer:
The project had a Bcrypt reference that block the connections to SQL. I delete all Bcrypt and add transport credentials to Windows in the app.config. any way thanks guys.

I cannot connect to the database in Visual Basic

I have the following code:
Dim string_conectare As String = "Data Source=|DataDirectory|\Database1.sdf"
Dim conexiune As SqlConnection
conexiune = New SqlConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
As you can see i would like to open a connection to the database but every time I want test it I get this 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: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)
I struggled for more than 2 hours, so please help me!
Later edit:
I've tried this:
Dim string_conectare As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database1.sdf;Persist Security Info=True"
Dim conexiune As OleDbConnection
conexiune = New OleDbConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
but it throw me this error:
Unrecognized database format
Here is an excerpt of the same code I use to connect to my databases:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
Try that.
Be sure to add the resource MySQL.Data into your project and also call it using:
Imports MySQL.Data.MySQLClient
ALSO! Be certain that when you created the database that you enabled external database access. If you don't do that then VB programs will not be able to access it and it will limit access to your webhost only.
The Jet OLEDB Provider is for Access databases. It can't handle sdf files. Try with the correct connection string.
You can take help of this website to get the correct connection string for your database:
www.ConnectionStrings.com
Is the application built on shared storage and you are trying to run it from local machine?
That could be an issue if the server containing the app does not have access to db

Using Object to execute SQL statements in Visual Studio

I apologize if my question is simple, but I have done a lot of looking on the Internet and I am having trouble finding a solution.
I have a database connected to Visual Studio where I used the "Connect to Database..." wizard to establish the connection. In the Server Explorer in Visual Studio, I see I have a Data Connection called "newreptDBtest.accdb", and a Server named Mandrew.
Basically I would like to execute SQL statements on this database when clicking a button. So I have a button on a form, and it has the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show("Error on connection")
End Try
If sqlconn.State = 1 Then
MessageBox.Show("Success!")
End If
End Sub
In General Declarations, I have:
Imports System.Data.SqlClient
Perhaps because it's not a SQL database? I'm not sure. Either way, I have not been able to achieve the "Success!" from the MessageBox. Once I've gotten that, I'm sure I can figure out how to create SQL statements to return certain rows or single pieces of information.
In the newreptDBtest, the table I'd like to be executing queries on is called newrept, and the connection string to the database is:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Andrew\Documents\newreptDBtest.accdb"
tl;dr:
How do I use an object (such as a button) to execute SQL queries on a table inside a database already connected to my project?
Thanks in advance
The classes that you need to use for accessing an MS Access database file are in the System.Data.OleDb namespace. Try this:
Dim ConnString As String = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Dim SqlString As String = "put your query here, e.g. Select * From Contacts"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
'access the data using the reader, e.g. reader("ColumnName")
End While
End Using
End Using
End Using
Taken from here
Obviously, you will need to modify it to fit your query but this hightlights the fact that you need to use OleDbConnection to connect to an MS Access file.

Resources