Method/Property Error on New SQL Server Connection - sql-server

I'm running VB .Net in VS2013, on a Windows 8 over SQL Server 2008 R2, and my creation of an SQL Connection is failing with the error:
Property access must assign to the property or use its value.
Here's my code:
Dim oCnn As SqlConnection
Dim sCnn As String
Dim bSunCnnOK as Boolean
Try
If vsSunServer <> "" Then
sCnn = "Provider=SQLOLEDB.1;" & _
"Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog=SunSystemsData;" & _
"Data Source=" & vsSunServer
oCnn = New SqlConnection(sCnn)
oCnn.Open()
bSunCnnOK = True
End If
Catch ex As Exception
bSunCnnOK = False
End Try
_vsSunserver_ is a string being passed in to the sub, and has a run-time value of "SVRSUN07".
The error is being raised on the line:
oCnn = New SqlConnection(sCnn)
So at run-time, sCnn holds:
"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SunSystemsData;Data Source=SVRSUN07"
I've lifted this connection string from a .udl file, which returns successful when I Test Connection.
I can run SQLSMS over this database OK.

Below is an ASCII art diagram that shows how the components related to each other. You are trying to use a SQL OLEDB connection string with SqlConnection. These things don't go together.
C#/VB.NET code -┬------------> SqlConnection -----------------┬-> SQL Server
| |
├--> OleDbConnection -┬-> SQL OLEDB provider -┤
| | |
| Native code --┤ |
| | |
└-> OdbcConnection ---┴-> SQL ODBC driver ----┘
If you really want to use the SQL OLEDB native provider then you can use OleDbConnection. This might be useful if you want your VB.NET code to be flexible and possible connect to other OLEDB providers such as Access, Postgres, Mysql, etc.
However if you know for sure that you will only be connecting to SQL Server then it will be easier to use SqlConnection instead with a connection string like "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SunSystemsData;Data Source=SVRSUN07".

Related

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.

Excel Visual Basic ADODB SQL connection string not working

I'm trying to connect to an SQL Server through Automatisation in VBA, so each time Excel starts, the SQL Statement updates the table in Excel.
Problem is, that my Connection string always throws an exception:
"Run-time error "-2147217843 (80040e4d)'; Automation error"
I have following data provided:
Servername, though it has a comma in it's Name
Database Name
I also have a Windows user (accountname & Password), that I run the Statements from, but I doubt, it is necessary to provide this information to the SQL Server.
the Connection string Looks as follows:
Public Sub OpenConnection2(pServer As String, pCatalog As String)
Dim mDataBase As New ADODB.Connection
Dim mRS As New ADODB.Recordset
Dim mCmd As New ADODB.Command
Call mDataBase.Open("Provider=SQLOLEDB;Initial Catalog=" & pCatalog & ";Data Source=" & pServer & ";")
mCmd.ActiveConnection = mDataBase
End Sub
As you, FunnyO, already stated, it is the connection string.
You probably do not have the correct driver definition.
Try something like that:
strCnn = "Provider=SQLNCLI11;Server=" & pServer & ";Database=" & pCatalog & ";Integrated Security=SSPI;"
Sure, a very simple connection string. But it should work out as it is a very common one...

How do I connect to SQL Server using VBA?

I want to automate some Mail Merge functionality using data drawn from a SQL Server Database. Here’s the code I’m using:
Sub open_DSN()
Dim strConnection As String
ActiveDocument.MailMerge.CreateDataSource Name:="DB-NAME", _
Connection:="Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE", _
SQLStatement:="select * from DataTable"
ActiveDocument.MailMerge.OpenDataSource Name:="DB-NAME"
If ActiveDocument.MailMerge.DataSource.Name <> "" Then _
MsgBox ActiveDocument.MailMerge.DataSource.Name
' – code lifted from MS Help within Word that seems the nearest to what I require
'With ActiveDocument.MailMerge
' .MainDocumentType = wdFormLetters
' strConnection = "DSN=MS Access Databases;" _
' & "DBQ=C:\Northwind.mdb;" _
' & "FIL=RedISAM;"
' .OpenDataSource Name:="C:\NorthWind.mdb", _
' Connection:=strConnection, _
' SQLStatement:="SELECT * FROM Customers"
'End With
With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
strConnection = "Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE"
.OpenDataSource Name:="DB-NAME", _
Connection:=strConnection, _
SQLStatement:="SELECT * FROM DataTable"
End With
End Sub
Unfortunately I can’t get this code to display the data. What am I doing wrong?
Did you replace "DB-NAME" and "DATA-SOURCE" with the actual values in the connection string?
So do you have a sql server instance called DATA-Source with a Database called DB-Name?
Probably not?
More Like MyServer\MyInstance and MyDatabase
I don't know MailMerge, so I can't comment on the code that you use to establish the connection.
But if you are sure that the code is okay, then it's probably the connection string.
There are lots of different possible connection strings to connect to SQL Server, so the right solution depends on your SQL Server version and setup (for example, Windows authentification or SQL Server authentification...).
This MSDN article which says that MailMerge supports OLE DB and ODBC, so you can use either of these.
If you tell us more about your SQL Server setup, we can help you find the correct connection string for your use case.

How do I connect to SQL Server with VB?

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! =)

Unable to connect to SQL2005 using VBScript

I have the following VBScript, which is supposed to connect to a SQL Server 2005 database. But, my connection is failing. Why?
Set dbConnection = CreateObject("ADODB.Connection")
dbConnString = "Provider=SQLOLEDB.1;Data Source=srv\test1;" & _
"Initial Catalog=tset_DB;user id ='abc';password='abc'"
'Open the connection
dbConnection.Open dbConnString
You don't need quotations around your username and password. Try this:
Set dbConnection = CreateObject("ADODB.Connection")
dbConnString = "Provider=SQLOLEDB.1;Data Source=srv\test1;" & _
"Initial Catalog=test_DB;user id =abc;password=abc"
'Open the connection
dbConnection.Open dbConnString
Also, your Initial Catalog was set to tset_DB, when I'm guessing it should be test_DB.
ConnectionStrings.com is a huge help for ensuring that your connection strings are valid.

Resources