Connecting to Data Sources in the Script Task - sql

I'm having some trouble using the connection manager from a script task in SSIS. The program will compile perfectly until I try using the connection that is set in the Environment.
Private Sub InsertLog(ByRef log() As String)
Dim conn As SqlClient.SqlConnection
conn = _
DirectCast(Dts.Connections("ConfigDB").AcquireConnection(Dts.Transaction), _
SqlClient.SqlConnection)
MsgBox(log(0) & " " & log(1) & " " & log(2) & " " & log(3) & Dts.Connections("ConfigDB").ConnectionString.ToString())
End Sub
If I comment out the Dim and DirectCast the package executes successfully and I can successfully get the connection string in a messagebox.
Data Source=PathToServer;Initial Catalog=DB;Provider=...;Integrated Security=...;Application Name=...;Auto Translate=False;
Has anyone else had this happen?

I have a solution. The reason why it failed was because of the Provider and Auto Translate, so my solution is to strip out what is not needed.
Dim strConnection As String = Dts.Connections("Automation").ConnectionString.ToString()
Dim regProvider As New Regex("Provider=([^;]*);")
Dim regTranslate As New Regex("Auto Translate=([^;]*);")
strConnection = regProvider.Replace(strConnection, "")
strConnection = regTranslate.Replace(strConnection, "")
Dim conn As New SqlClient.SqlConnection(strConnection)

Related

SQL query returning 'Overload resolution error'

I have a readini file to connect to my SQL Server table, and in my query code to display data from it, I'm getting an error that I've not been able to solve, is there anybody here who can?
This is the error:
Error 1
Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Sub New(selectCommandText As String, selectConnection As System.Data.OleDb.OleDbConnection)': Value of type 'SQLServerApplication.readini' cannot be converted to 'System.Data.OleDb.OleDbConnection'.
'Public Sub New(selectCommandText As String, selectConnectionString As String)': Value of type 'SQLServerApplication.readini' cannot be converted to 'String'.
This is the code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class frmViewDtb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As readini = New readini()
connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
End Sub
End Class
The line that the error is occurring on is line 13:
Dim da As New OleDbDataAdapter(sql, connection)
Code for getConnectionString;
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
End Function
Thanks in advance if you can get it!
I believe you are getting the error as the constructor for OleDbDataAdpater is expecting two strings and your connection variable isn't a string. I suspect your code needs to look like this:
Dim connection As readini = New readini()
Dim ConnString = connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, ConnString)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
The getConnectionString method also needed amending to add the Return statement:
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
Return s
End Function

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.

VB.NET Update to Excel

I am developing an application in Visual Basic using Visual Studio 2013. In this application I am attempting to use an oledb UPDATE to write data out to an Excel spreadsheet treated as a database. I have tried numerous different formats of this but I either get a syntax error or it pretends to work but nothing actually gets written to the file. Can anyone tell me what is wrong with this code:
Public Function WriteToExcel(ExcelPath As String, dtUser As DataTable)
Dim vOffice As String = dtUser.Rows(0).Item("Office").ToString
Dim vDivision As String = dtUser.Rows(0).Item("Division").ToString
Dim vSection As String = dtUser.Rows(0).Item("Section").ToString
Dim vUser As String = dtUser.Rows(0).Item("UserID").ToString
Dim ExcelconnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelPath & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
Dim BatchID As Long = 0
Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice WHERE [Primary User] = #uUser"
'Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice, " & _
'"Division = #uDivision, " & _
'"Section = #uSection " & _
'"WHERE [Primary User] = #uUser"
Using conn As New OleDb.OleDbConnection(ExcelconnString)
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#uOffice", vOffice)
cmd.Parameters.AddWithValue("#uDivision", vDivision)
cmd.Parameters.AddWithValue("#uSection", vSection)
cmd.Parameters.AddWithValue("#uUser", vUser)
Try
MessageBox.Show("Attempting to update " & vUser & ". " & vOffice & ", " & vDivision & ", " & vSection & "!")
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & vbNewLine & ex.StackTrace)
End Try
End Using
End Function
Your SQL has two issues:
OleDbCommands use question marks ? as the placeholder for parameters, not #parameterName (that's for SqlCommands).
Section is a reserved keyword, so it needs to be escaped: [Section].

adding connection string during installation of vb.net project

I want to create an installer wherein the user specifies where the connection string of the database.
I've seen a articles like this but they're in C#.
like this one: http://www.codeproject.com/Tips/446121/Adding-connection-string-during-installation
I also tried to translate the code into vb.net but there are some errors I can't fix.
If anyone can tell me how to do it or any article that might help me is really a great help.
I want to do this in my vb.net project not in C#
Here is the code converted to VB .NET
'Installer.vb
Dim dataSource As String = "Data Source=" & Context.Parameters("DataSource")
Dim initialcatalog As String = "Initial Catalog=" & Context.Parameters("InitialCatalog")
Dim user As String = "User ID=" & Context.Parameters("UserID")
Dim password As String = "Password=" & Context.Parameters("Password")
dataSource = dataSource & ";" & initialcatalog & ";" & user & ";" & password
dataSource = dataSource
MessageBox.Show("instance=" & dataSource)
Dim map As New ExeConfigurationFileMap()
MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().Location & ".config")
'Getting the path location
Dim configFile As String = String.Concat(System.Reflection.Assembly.GetExecutingAssembly().Location, ".config")
map.ExeConfigFilename = configFile
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None)
Dim connectionsection As String = config.ConnectionStrings.ConnectionStrings("MyConnectionString").ConnectionString
Dim connectionstring As ConnectionStringSettings = Nothing
If connectionsection IsNot Nothing Then
config.ConnectionStrings.ConnectionStrings.Remove("MyConnectionString")
'MessageBox.Show("removing existing Connection String")
End If
connectionstring = New ConnectionStringSettings("MyConnectionString", dataSource)
config.ConnectionStrings.ConnectionStrings.Add(connectionstring)
config.Save(ConfigurationSaveMode.Modified, True)
ConfigurationManager.RefreshSection("connectionStrings")

"Could not find installable ISAM" error in VB.NET

Im new to visual basic.. I would like to ask on how to fixed the problem "Could not find installable ISAM.". I used Visual Basic as programming language. I used MS access as the database. My program is to fetch data from access. This would be my code.
Imports System.Data.OleDb
Module Main
Dim mDataPath As String
Sub Main()
GetPupils()
Console.ReadLine()
End Sub
Private Function GetConnection() As OleDb.OleDbConnection
'return a new connection to the database5
Return New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Database Password=oNer00FooR3n0 " & "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb")
End Function
Public Function GetPupils() As DataSet
Dim conn As OleDb.OleDbConnection = GetConnection()
Try
Dim ds As New DataSet 'temporary storage
Dim sql As String = "select * from SESSIONS" 'query
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, conn) 'connection
Try
da.Fill(ds, "SESSIONS") 'fetch data from db
Finally
da.Dispose() 'in case something goes wrong
End Try
Dim startVal = 0 'first record
Dim endVal = ds.Tables(0).Rows.Count 'total number records
For var = startVal To endVal - 1 'display records
Console.WriteLine(ds.Tables(0).Rows(var).Item(0).ToString() + " " + ds.Tables(0).Rows(var).Item(1).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString()) 'code for display id and name
Next
Return ds
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Module
I would like to know what is the cause of the error so that I can proceed to my program.. Thank you so much for the feedback..
You seem to be missing a delimiter after your password attribute.
I think you also need to use Jet OLEDB:Database Password=... instead (if indeed you have an access database protected with a password):
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb;" _
& "Jet OLEDB:Database Password=oNer00FooR3n0;"
Missing ; delimiter here:
...Password=oNer00FooR3n0 " & "Data Sourc...
Needs to be
...Password=oNer00FooR3n0 " & ";Data Sourc...
Also just Password instead of Database Password.
Initially, i too got this sort of error, but when i wrote the connection string in a single line (i mean without using [& _] or breaking in 2 lines, then this worked properly.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\USER1\Desktop\MSaccessDB\MSaccessDB\my_database_file.mdb;Database Password=MyPassword"
Hope this helps.
Mukesh L.