Unable to connect to SQL2005 using VBScript - sql-server-2005

Using the connection string below I can connect to a SQL2000 DB but not a SQL2005. I have the code in an ASP file.
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open cn
set rs= server.CreateObject("ADODB.Recordset")
rs.CursorLocation=3
rs.Open sql,cn,3,4
if not rs.EOF then
Response.Write("<b>Column1: " & rs("Column1") & "</b><br />")
end if
set rs.ActiveConnection= nothing
rs.Close
set rs= nothing
if ucase(TypeName(cn)) = "CONNECTION" then
cn.Close
Set cn = Nothing
end if
I have even tired with SQLOLEDB.1
Sql login is enabled on the sql server.
Error: The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Happens on rs.Open sql,cn,3,4

It happens to everybody sometime:
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open connStr
You are calling a variable conn as connection string but you have declared and filled connStr
Change "cn.Open conn" with "cn.Open connStr"

What is the error? SQL Server 2005/8 install with remote connections disabled -- check this support article.
I see, try setting your connString on your Connection object (you use conn instead of connStr). Uee option explicit to avoid these errors.

Related

Getting insertID using currentproject.connection

I wanted to get the insert ID of the the last insert query
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.Connection
cn.Execute "Insert into Locations(locationName) Values('" & Me.location.Value & "')"
rs.Open "SELECT ##identity AS locationID FROM locations", cn
Debug.Print rs.Fields("locationID")
However, this always returns 0 . Is there a way to get the insertID using the ADO connection?
Edit1:
With the help of the reply below and further research I found out the soultion
I forgot to mention that my backend database is mysql database not MSSQL or Access. I also changed my code to use global connection now which is named g_cn. I think currentproject.connection does not work with backend mysql database to get the insertionID because it uses DAO connection.
I set the global connection by doing:
g_cn.Open "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=" & gc_DevServerName & ";Database=" & gc_DevDBName & ";Uid=" & gc_DevUser & ";Pwd=" & gc_DevPassword & ";Option=3;"
I can now use ADO. So my code changed to :
Dim rs As New ADODB.Recordset
rs.Open "Insert into Locations(locationName) Values('" & Me.location.Value & "')", g_cn
rs.Open "Select LAST_INSERT_ID() as last from locations;", g_cn
Debug.Print rs.Fields("last")
rs.Close
SELECT ##identity is a special query in Access. You can't use it with a FROM clause. Remove that and the query will work:
rs.Open "SELECT ##identity AS locationID", cn

ADODB connection parameter issue

I am getting error as
Too few parameters expected 1
on below line. Please assist
mrs.Open sSQLSting, Conn, 3, 1
Complete coding
Dim Conn As New adodb.Connection
Dim mrs As New adodb.Recordset
Dim DBPath As String, sconnect As String
DBPath = ThisWorkbook.FullName
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLSting = "SELECT * From [DataSheet$A1:D5325] where [Vertical Name]= '" & Sheets(1).ComboBox1.List(i) & "'"
mrs.Open sSQLSting, Conn, 3, 1
Sheets("Sheet4").Cells(lastrow, 4).Value = mrs.RecordCount
mrs.Close
Conn.Close
Yes the error message is not very intuitive :(
That is because when the field names in your SQL query do not match the table fields name:
Too few parameters expected 1
means that 1 filedname that you are using in your SQL-Statement is not available in your table.
So probably a field called Vertical Name does not exist!
I also highly recommend to use Option Explicit and declare all your variables properly to avoid mistyping in variable names: Eg. sSQLSting was obviously meant to be sSQLString. If you don't use Option Explicit you will run into issues soon.
Further to my comment, I have mocked up some dummy data, and the following works
Sub Data_Extract()
Dim c As New ADODB.Connection
Dim r As New ADODB.Recordset
Dim s As String
s = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Workspace\Dummy Data\SAMPLE_GENERAL.xlsx;" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
c.Open s
r.Open "Select * from [Sheet1$A1:E5] where [field 1]='b'", c, 3
End Sub

How to connect to Netezza (PureData System for Analytics) via VBA

I am trying to connect to connect to Netezza using VBA. I have enabled the following:
Microsoft Excel 15.0 Object Library
Microsoft Office 15.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Visual Basic for Applications
Here is my code:
Sub NZConn()
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim x As Variant
Set cmd = New ADODB.Command
Set RS = New ADODB.Recordset
cmd.ActiveConnection = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.CommandTimeout = 120
cmd.CommandType = adCmdText
x = "Write Query here"
cmd.CommandText = x
Set rs = cmd.Execute
Sheet1.Range("A1").CopyFromRecordset rs
cmd.ActiveConnection.Close
End Sub
I can get the code to run without throwing back an error, but there is nothing that is pasted from the record set, which leads me to believe that is may have something to do with the structure of the connection string.
I have the server, user id, password, database, port, and driver.
Would I need to establish / open an ActiveConnection first?
I was able to figure out the issue on my own. I found that there is a command line builder in the 'Tools' tab in Aginity, which helped specify the exact connection string I needed to connect to Netezza. Once I had this connection string, I was getting an 'architecture mismatch' error. After downloading the 32-bit ODBC drivers for Netezza, the methodology worked perfectly. Here is the updated code below:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String, ConnectionString As String
Dim Server As String, Query As String
Dim SQLTable As Worksheet
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Set SQLTable = Sheet1
Server = SQLTable.Cells(2,3).Value
User = SQLTable.Cells(2,4).Value
PW = SQLTable.Cells(2,5).Value
DB = SQLTable.Cells(2,6).Value
Query = SQLTable.Cells(2,7).Value
ConnectionString = "Driver={NetezzaSQL};" & _
"server=" & Server & ";" & _
"UserName=" & User & ";" & _
"Password=" & PW & ";" & _
"Database=" & DB & ";" & _
"Query Timeout=120"
cn.Open (ConnectionString)
rs.Open (Query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Worksheets("Sheet2").Cells(2, "A").CopyFromRecordset rs
rs.Close
cn.Close
NB:
"IBM NETEZZA ODBC DRIVER – 32 BIT" is what I downloaded
"ODBC-DRIVER-FOR-NETEZZA-7-X86" is what showed up in my software center to install
"Name: NetezzaSQL ; Version: 7.00.04.41188 ; Company: www.ibm.com ; File: NSQLODBC.DLL" is what is shown now in my 32-bit 'ODBC Data Source Administrator' window
I think your connection string is ok, and yes you should need to open a connection first.
Like this:
AccessConnect = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
Dim Conn1 As New adodb.Connection
Conn1.ConnectionString = AccessConnect
Conn1.Open
then it would be
Set RS = Conn1.Execute(x) 'where x is your query

How do I turn a QueryTable Connection into an ADODB connection?

I'm trying to update an old excel sheet that uses QueryTables to connect to a Microsoft SQL Server.
The following is working:
With ActiveSheet.QueryTables.Add(Connection:= _
"ODBC;DSN=[dbname];UID=[name];PWD=[pass];APP=Microsoft Office 2003;WSID=[machine name];DATABASE=[dbname];AutoTranslate=No;QuotedId=No;AnsiNPW=No" _
, Destination:=Range("A20"))
.CommandText = Array("[a valid query]")
There are some more sophisticated things I want to be able to do with the information this QueryTable is getting, but I keep getting the following error:
Run-time error '-2147467259 (80004005)': [DBNETLIB][ConnectionOpen (Invalid Instance()).]Invalid connection.
with the following code:
Private SqlConn As ADODB.Connection
Private Sub InitiateSqlConn(Optional User As String, Optional Pass As String, Optional Server As String, Optional DB As String)
If SqlConn Is Nothing Then
Dim strConn As String
Set SqlConn = New ADODB.Connection
If IsNull(User) Or IsEmpty(User) Or User = "" Then
User = "[user]"
End If
If IsNull(Pass) Or IsEmpty(Pass) Or Pass = "" Then
Pass = "[pass]"
End If
If IsNull(Server) Or IsEmpty(Server) Or Server = "" Then
Server = "[ServerName]"
End If
If IsNull(DB) Or IsEmpty(DB) Or DB = "" Then
DB = "[DBName]"
End If
strConn = "Provider=SQLOLEDB;Data Source=" & Server & ";Initial Catalog=" & DB & ";"
SqlConn.Open "Provider=SQLOLEDB;Data Source=[SeverName];Initial Catalog=[DBName];Trusted_connection=yes;", "[User]", "[Pass]"
End If
End Sub
Public Sub QueryInto(QR As String, ByRef RS As ADODB.Recordset, Optional User As String, Optional Pass As String, Optional Server As String, Optional DB As String)
InitiateSqlCon User, Pass, Server, DB
RS.Open QR, SqlConn
End Sub
I have also tried:
SqlConn.Open "Driver={SQL Server};Server=[SeverName];Database=[DBName];UID=[User];PWD=[Pass];"
And I get the following error:
Run-time error '-2147467259 (80004005)': [Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection.
Errors always occur on SqlConn.Open.
How do I get the connection that is established with the QueryTable to be established as an ADODB.Connection object ?
This one will fail because you are appending extra text after the "Trusted_connection" parameter. If you use a trusted connection, you don't need a username or password, and the syntax is different for SQLOLEDB than with {SQLServer} (it should be Integrated Security=SSPI;.
SqlConn.Open "Provider=SQLOLEDB;Data Source=[SeverName];Initial Catalog=[DBName];Trusted_connection=yes;", "[User]", "[Pass]"
You also need to build the Data Source and Initial Catalog into the string instead of Data Source=[SeverName] and Initial Catalog=[DBName].
This one will fail because you aren't using any security parameters:
strConn = "Provider=SQLOLEDB;Data Source=" & Server & ";Initial Catalog=" & DB & ";"
This one fails because for the same reason as the first. You need to build the actual parameters into the connection string.
SqlConn.Open "Driver={SQL Server};Server=[SeverName];Database=[DBName];UID=[User];PWD=[Pass];"
It should look something more like this:
Private Sub InitiateSqlConn(Optional User As String, Optional Pass As String)
If SqlConn Is Nothing Then
Dim strConn As String
Dim Server As String
Dim DB As String
'These can't be optional. They are required.
Server = "TheActualNameOfTheServerHere"
DB = "TheActualNameOfTheDatabaseHere"
Set SqlConn = New ADODB.Connection
If User = vbNullString Or Pass = vbNullString Then
'No credentials. Try a trusted connection.
strConn = "Provider=SQLOLEDB;Data Source=" & Server & _
";Initial Catalog=" & DB & ";Integrated Security=SSPI;"
Else
'Credentials.
strConn = "Provider=SQLOLEDB;Data Source=" & Server & _
";Initial Catalog=" & DB & ";User Id=" & User & _
"; Password=" & Pass & ";"
End If
SqlConn.Open strConn
End If
End Sub
Note that the Server and DB parameter cannot be optional. They are in fact required and must be valid in order to connect. You can also skip the null and empty checks for optional string parameters unless you're doing something really strange. They will default to vbNullString if nothing is passed.

User defined function type not defined while creating connection to database

While opening database connection I get an error
User defined type not defined
I am able to create connection in same macro, but I have to create function for connection to use any were in project.
Option Explicit
Public CN As ADODB.Connection
Public Function Connection() As ADODB.Connection
If CN Is Nothing Then
Set CN = New ADODB.Connection
Dim Con_str As String
Con_str = "Provider=SQLOLEDB;Persist Security Info=True;User ID=" & getvalue("User_id") & _
";Password=" & getvalue("Password") & _
";Initial Catalog=" & getvalue("Database_Name") & _
";Data Source=" & getvalue("Server_Name") & ";"
Debug.Print Con_str
CN.Open Con_str
End
Set Connection = CN
End Function
Sub teting()
Dim rs As ADODB.Recordset
rs.Open connetion(), adOpenStatic 'CreateObject("ADODB.Connection")
ActiveSheet.range("A10").CopyFromRecordset rs
End Sub
What is the actual cause of this issue?
Thanks,
Uttam Patel
You need to enable Microsoft ActiveX Data Objects x.x Library, where x.x is replaced by the version number that you have available.
You'll find it under tools --> references in the VBA editor.