How to connect to Sql Server 2008 database from Visual Basic 6? - sql-server

What is the correct connection string and what are the requirements for connecting to Sql Server 2008 database from Visual Basic 6?

' Initialize variables.
Dim cn As New ADODB.Connection
Dim provStr As String
' Specify the OLE DB provider.
cn.Provider = "sqloledb"
' Specify connection string on Open method.
ProvStr = "Server=MyServer;Database=northwind;Trusted_Connection=yes"
cn.Open provStr
For illustration only (Ref.):
Set rsOrders = New Recordset
rsOrders.Open "Select * from orders", cn
Do While Not rsOrders.EOF
'
' If the order matches some custom business logic then get the details for
' that order, without opening a new connection.
'
If SomeBusinessLogic(rsOrders("CustomerID")) Then
Dim rsDetails As Recordset
Set rsDetails = New Recordset
'
' Open a new recordset using the same connection. Normally it's not
' possible to have two recordsets simultaniously using the same
' connection, but MARS makes this possible
'
rsDetails.Open "Select sum(quantity * unitprice) as total " & _
"from [order details] " & _
"where OrderID=" & rsOrders("OrderID"), _
cn
grandTotal = grandTotal + rsDetails("total")
End If
rsOrders.MoveNext
Loop
lblTotalOrders = grandTotal

You would use ADODB. And here are some connection string samples.

Public Cnn As New ADODB.Connection
Cnn.Open Provider=SQLNCLI10;Server=10.1.100.1;Database=DataJualLama;Uid=sa;Pwd=sa;
It required to install sql server 2008 native client runtime from microsoft site.

Related

Connect to SQL Server in VBA if the server requires specific username and password?

I realized today that when you connect to SQL Server data source in Excel's native connection, it doesn't allow you to enter in a specific username and password. It just asks for server name and database.
In VBA , under the assumption that I wanted to import data from a SQL Server data query into Sheet1, can you please help me understand how to write that code?
For purposes of this exercise:
SQL Server Connection INFO
Server Name: TestingS,1633
Database Name: CarSales
username: car
password: sales
The query I want to run for simplicity sake can be: "select * from table"
I have been doing some research , but am getting a bit lost. I have no problem setting up standard queries with custom SQL via ODBC, but because I need VBA, it's very tricky for me. Please help.
This is an example of MSSQL.
Sub testMSSQL()
'Reference Microsoft ActiveX data object Library 2.8 ~~
Dim cnn As ADODB.Connection
Dim strSQL As String
Dim Ws As Worksheet
Set Ws = ActiveSheet
strSQL = "select * from table"
Set cnn = New ADODB.Connection
'Set the provider property to the OLE DB Provider for ODBC.
'cnn.Provider = "MSDASQL"
'cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
'cnn.Provider = "MSOLAP"
cnn.Provider = "SQLOLEDB.1" '<~~ mssql
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=TestingS;uid=car;pwd=sales;database=CarSales"
Set rs = New ADODB.Recordset
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Not connected server"
Exit Sub
End If
If Not rs.EOF Then
With Ws
.Range("a1").CurrentRegion.ClearContents
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next
.Range("a2").CopyFromRecordset rs
.Columns.AutoFit
End With
Else
MsgBox "No Data!!", vbCritical
End If
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub

JOIN an Access table and a SQL Server table in a single query from Excel VBA

I am using Excel 64-bit
I have a ms-access database and in this database I have normal ms-access table and some linked table from SQL Server, I have a query that is taking a reference of a linked table, and when I am firing that query from excel vba it is giving me an ODBC error, however I am successfully able to fetch non linked table from excel vba.
Now I am thinking about different approach, can it be possible to join ms-access and SQL Server table in a single query, I found some code from net and tried my luck, but it is not working and giving an error message "Could not find installable ISAM", below is the code that I am using.
Note:- table "PeopleMain" is a sql server table, and except this table all are ms-access table.
[code]
Sub FetchData3()
Dim rs As Object
Dim cn As Object
Dim ss As String
Dim conn As String
Dim accdb As Object
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\PI Database.accdb;Persist Security Info=False;Mode=Read"
ss = "SELECT RM.ReconciliationID, RM.FirmID, RM.FirmName, RM.DateRequested, RM.DueDate, Rm.ExtendedDueDate, " & _
"Requestor.Name, SecondaryRequestor.Name FROM " & _
"((ReconciliationMaster RM INNER JOIN Reconciliation_Fund RF ON RF.ReconciliationID = RM.ReconciliationID) " & _
"LEFT JOIN (SELECT Preferred_Name + ' ' + Last_Name AS Name, People_ID FROM " & _
"[Provider=sqloledb;Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain) Requestor " & _
"ON Requestor.People_ID = RM.PrimaryRequestor) LEFT JOIN (SELECT Preferred_Name + ' ' + Last_Name AS Name, " & _
"People_ID FROM [Provider=sqloledb;Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain) " & _
"SecondaryRequestor ON SecondaryRequestor.People_ID = RM.SecondaryRequestor WHERE RM.ReconciliationID = 522;"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open conn
rs.Open ss, cn
Sheet1.Cells.ClearContents
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
MsgBox "done"
End Sub
Thanks
Kashif
Access allows querying and joining in ODBC data sources, not OLEDB data sources.
Change the connection string used inside your query to an ODBC string:
[ODBC;Driver={SQL Server};Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain
When available, I recommend using a more up-to-date ODBC driver, of course.

VBA connecting to SQL Server Express database issue

I installed a copy of SQL Server Express (latest). I am having trouble connecting to it.
Since I am the admin on this computer, it should be not needing user name password, because I created the database, and everything should fall under Windows authentication. My code is below.
I get an error:
Run-time error '-2147217843 (80040e4d)':
Invalid authorization specification
This error happens on attempting to open the connection.
When I launch a subform from main form, this code runs in initialize:
Option Explicit
Private objMyConn As ADODB.Connection
Private objMyRecordset As ADODB.Recordset
Private Sub UserForm_Initialize()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;"
objMyConn.Open
strSQL = "Select * from Contact where Lastname like " + Chr(39) + "%" + LastSearch + Chr(39) + " And Firstname like " + Chr(39) + "%" + FirstSearch + Chr(39)
MsgBox strSQL
End Sub
Add Integrated Security=SSPI to your connection string to indicate a trusted connection is desired:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;Integrated Security=SSPI"
EDIT
SQL Server Express installs a named instance by default so you may need to change the data source to include the instance name:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=Contact;Integrated Security=SSPI"
use something like this instead of localhost
HP8300-0792\SQLEXPRESS
where HP8300-0792 is the name of your computer.

while exporting data to excel from sql using openrowset getting error

I am getting error while exporting data from SQL to already created .xlsx file. I used openrowset.
It works fine most of times, but when the data comes in of the field as a large string, while inserting in excel it shows error as:
the statement has been terminated , string or binary data would be
truncated.
Data gets inserted in table but while inserting in excel this error comes.
Please help me find the solution.
So, going form SQL Server to Excel, you can do many things. Check out thins link:
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
Also, here is some VBA code to move data from SQL Server to Excel:
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub

Using a Parameterized Query on a SQL Table in Excel using VBA

I have some code that is supposed to run a parameterized query of the SQL table that I am query. The way that it does this is there is a designated cell (Z1) that is supposed to take in an input value from one of my columns and then automatically update the query to display the results in the excel table. I keep getting a run-time error: '1004' which says it's a General ODBC error, but I'm not sure what is happening. Here is the database that I am connection to: Database
I'm using SQL express, so the server is .\SQLEXPRESS
Here is the code that I have:
Sub ParameterQueryExample()
'---creates a ListObject-QueryTable on Sheet1 that uses the value in
' Cell Z1 as the ProductID Parameter for an SQL Query
' Once created, the query will refresh upon changes to Z1.
Dim sSQL As String
Dim qt As QueryTable
Dim rDest As Range
'--build connection string-must use ODBC to allow parameters
Const sConnect = "ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=.\SQLEXPRESS;" & _
"Database=TSQL2012;" & _
"Trusted_Connection=yes"
'--build SQL statement
sSQL = "SELECT *" & _
" FROM TSQL2012.Production.Products Products" & _
" WHERE Products.productid = ?;"
'--create ListObject and get QueryTable
Set rDest = Sheets("Sheet1").Range("A1")
rDest.CurrentRegion.Clear 'optional- delete existing table
Set qt = rDest.Parent.ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=Array(sConnect), Destination:=rDest).QueryTable
'--add Parameter to QueryTable-use Cell Z1 as parameter
With qt.Parameters.Add("ProductID", xlParamTypeVarChar)
.SetParam xlRange, Sheets("Sheet1").Range("Z1")
.RefreshOnChange = True
End With
'--populate QueryTable
With qt
.CommandText = sSQL
.CommandType = xlCmdSql
.AdjustColumnWidth = True 'add any other table properties here
.BackgroundQuery = False
.Refresh
End With
Set qt = Nothing
Set rDest = Nothing
End Sub
Open up the ODBC Data Source Admin program in Control Panel\System and Security\Administrative Tools and check that the driver you specified in the code "Driver={SQL Server Native Client 10.0};" matches a driver under the Drivers tab. A mismatch can give this error.

Resources