Using dynamic connection strings to connect to sybase via vb.net - vb.net

I need you help to get the syntax for assigning the server, port and database name using parameters.
the script works perfectly fine if I pass the variable in the command explicitly.
Dim myConn1 As Odbc.OdbcConnection = New Odbc.OdbcConnection("Driver=Adaptive Server Enterprise;uid=XXX;server=& SRVR &;port=& PRT &;database=& dbname &;pwd=XXX")
Please advise me where am I going wrong.request for Your prompt assistance.
Thanks
Mayur

You're not actually concatenating any strings. How many double quotes are there in this:
"Driver=Adaptive Server Enterprise;uid=XXX;server=& SRVR &;port=& PRT &;database=& dbname &;pwd=XXX"
There are exactly two, which means that that whole thing is one string. If you want to join multiple strings then there have to actually be multiple strings:
"Driver=Adaptive Server Enterprise;uid=XXX;server=" & SRVR & ";port=" & PRT & ";database=" & dbname & ";pwd=XXX"
You can avoid silly issues like this by not using string concatenation in the first place. You could use String.Format or, in VB 2015, string interpolation to make things clearer or you could do what you're supposed to do when building a connection string from parts and use a connection string builder. As you're building an ODBC connection string, you would use the OdbcConnectionStringBuilder class:
Dim builder As New OdbcConnectionStringBuilder("Driver=Adaptive Server Enterprise;uid=XXX;pwd=XXX")
builder("server") = server
builder("port") = port
builder("database") = database
Using connection As New OdbcConnection(builder.ConnectionString)
'...
End Using

Related

Read Value from Database in TextBox when Combobox text changes VB.NET

I have a list of Users Names in ComboBox and Some TextBoxes. When ComboBox text changes (i.e I select some username from ComboBox), The TextBoxes are filled with user details from the database.
I have code to achieve this in SQL Database. But these queries are not working with MsAccess database.
MysqlConn = New MySqlConnection
Mysql.ConnectionString = "server=localhost;user=root;password=root;database=database"
Dim READER As MySqlDataReader
Try
MysqlConn.open()
Dim Query As String
Query("select * from database.usernames where name='" & ComboBox1.Text & "'")
Command = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetString("name")
End While
End Try
Here is my answer. Please don't get overwhelmed by it. ;)
Broken code
First of all, as I see it, the code you provided cannot work at all, because:
your Query variable is initialized in an invalid (or at least a very exotic) way. You probably want to use something like:
Dim Query As String
Query = "select * from database.usernames where name='" & ComboBox1.Text & "'"
or in a single line:
Dim Query As String = "select * from database.usernames where name='" & ComboBox1.Text & "'"
you try to assign the connection string to the ConnectionString property of a nonexistent Mysql variable. Or the variable exists because it is declared somewhere else, which might be a bug in your code snippet here. But I assume you want to assign the connection string to the MysqlConn.ConnectionString property instead.
you have not declared the MysqlConn and Command variables anywhere. You only just assign to them. (I will simply assume you have declared the variables correctly somewhere else in your code...)
the IDataRecord interface does not provide a GetString(name As String) method overload. So unless you have defined a custom extension method for it, you probably need to use the IDataRecord.GetOrdinal(name As String) method as well, or use the column index instead of the column name.
Anyway, the code you provided uses MySQL. So I assume that MySQL is the "SQL Database" you are using successfully. And that seems to work, as you say? Well... Hmmm... Then I will simply assume your code snippet is completely correct and works perfectly with MySQL... :/
MS Access vs. MySQL
Using MS Access requires other data access classes (probably the ones in namespace System.Data.OleDb) and another connection string. You could take a look at this ADO.NET OleDb example for MS Access in the Microsoft documentation.
You probably even have to update your SQL query, because every database system uses its own SQL dialect. You might want to consult the Office documentation for that. But your query is quite simple, so perhaps all you have to do to make it work with MS Access is:
remove the database name and use only the table name, and
delimit the name identifier (since it is a reserved keyword in MS Access).
I personally delimit all identifiers in my SQL queries, just to avoid unintended conflicts with reserved keywords. So I would personally use something like this:
select * from [usernames] where [name] = '...'
Additional tips
Also, I would like to provide you some additional (unrelated) tips regarding improving your code:
Use Using-statements with variables of an IDisposable type as much as possible. Those types/classes do not implement that interface if there isn't a good reason for it, so I consider it not unimportant to call Dispose when you are done with such disposable objects (or using a Using statement to call Dispose implicitly).
Use SQL parameters (if possible) to avoid SQL injection vulnerabilities. Look at this StackOverflow question and its answer for an example of how to use SQL parameters with MS Access.
Example
You may take a look at the following code snippet. It might not provide a working example out-of-the-box, but you might get some useful/practical ideas from it:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\database.mdb;User Id=admin;Password="
Dim query As String = "select * from [usernames] where [name] = #Name"
Using conn As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query)
command.Parameters.Add("#Name", OleDbType.VarChar, 50).Value = ComboBox1.Text
conn.Open()
Using reader As OleDbDataReader = command.ExecuteReader
If reader.Read Then
textbox1.Text = reader.GetString(reader.GetOrdinal("name"))
End If
End Using
End Using
End Using

How to get the SQL server linked tables are connected to using VBA?

Is there a way to know which SQL Server the linked tables in MS Access database are pointing to using the ODBC connection?
I used the code below but I got the database name only and not the SQL server name.
Private Function checkconn()
Dim strConnect As String
Dim lngLocation As String
strConnect = CurrentDb.TableDefs("dbo_buh_summary").Connect
lngLocation = InStr(strConnect, ";DATABASE=")
If lngLocation <> 0 Then
GetDataPath = Mid(strConnect, lngLocation + 10)
End If
End Function
Assuming you used a FILE dsn to original link the tables?
(or a DSN less). I strong, but rather strong recommend you link always using a FILE dsn (not system or user). The reason is Access converts these links to DSN-less for you automatic. (and thus you don't need to setup a DSN on each computer).
Having noted the above? You can grab the server and the database name with this:
Sub m34343()
Dim strCon As String
strCon = CurrentDb.TableDefs("dbo_tblHotels3").Connect
Debug.Print strCon
Debug.Print Split(Split(strCon, "SERVER=")(1), ";")(0)
Debug.Print Split(Split(strCon, "DATABASE=")(1), ";")(0)
End Sub
Output:
ODBC;DRIVER=SQL Server;SERVER=ALBERTKALLAL-PC\SQLEXPRESS;
Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=test3
ALBERTKALLAL-PC\SQLEXPRESS
test3
So, I in above printed out the connection string, but then the next two lines grabs the server and the database name.

Accessing Oracle SQL Developer database from VBA

New to VBA and returning to SQL after 15 years. I'm am trying to use VBA to run SQL commands to download data into excel for further manipulation.
I have SQL Developer installed on my machine and I am able to access the database using the UI. I have figured out how to connect to the database and run a query within the SQL Developer interface, but honestly, I'm not an IT guy.
Any ideas how to do this? Even basic command line commands to connect to the database and run the query would be helpful.
I found this code on another site, but I'm having trouble getting my connection string to work. My macro errors out on the cnn.Open statement and says the Provider is not installed. I think it's because PROVIDER is set up for a different SQL Database type, but I can't seem to get the connection string to work.
I know my username and password, which I have successfully used to connect in the SQL Developer UI. I'm not sure what to put for remote IP address or database. Would that be the hostname and the SID in the connection properties dialog in SQL Developer? (The hostname looks more like a url without the http than an ip address. Not sure if hostname and ip address is an interchangeable term).
Sub Download_Reports()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=ORAOLEDB.ORACLE;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
I'm needing help with my connection string. Can anyone help me with this?
I'm connecting to a database via Oracle SQL Developer. I am able to connect within the UI by providing the following items:
Connection Name - got it.
myUsername - got it.
myPassword - got it.
Connection Type = Basic, Role = default
myHostname - got it.
myPort - got it.
mySID - got it.
However, I am unable to get my connection string to work in VBA. When I run the script I get
"Run-time Error '3076'. Provider cannot be found.
It may not be properly installed" on the line beginning with cnn.open.

Connect to SQL via ODBC using a .bat

I am currently performing a SQL query using Oracle SQL Developer and pasting in a standard query (same SELECT every time), then exporting to a csv file. I would like to execute the query via a batch file and place the output in a specified folder. I already use many batch files on this machine and would like to make this query part of a routine.
My machine has an existing ODBC connection to "WHPROD", but I do not know how to use it. Is there a way to connect to WHPROD from a batch file?
This is hardly possible in batch script directly without going overcomplicated
However it is simple to do it with VBscript, and since you can call your VBscript from a batch script, the result will be exactly what you want.
Here's an example of how to connect to Oracle and retrieve the results of a SELECT from VBS : (source)
Dim strCon
strCon = “Driver={Microsoft ODBC for Oracle}; ” & _
“CONNECTSTRING=(DESCRIPTION=” & _
“(ADDRESS=(PROTOCOL=TCP)” & _
“(HOST=Server_Name)(PORT=1521))” & _
“(CONNECT_DATA=(SERVICE_NAME=DB_Name))); uid=system;pwd=system;”
Dim oCon: Set oCon = WScript.CreateObject(“ADODB.Connection”)
Dim oRs: Set oRs = WScript.CreateObject(“ADODB.Recordset”)
oCon.Open strCon
Set oRs = oCon.Execute(“SELECT name from v$database”)
While Not oRs.EOF
WScript.Echo oRs.Fields(0).Value
oRs.MoveNext
Wend
oCon.Close
Set oRs = Nothing
Set oCon = Nothing
And here's how to call your VBS from the batch script :
#echo off
start "C:\\yourbatchfolder\\yourscript.vbs"
I wrote an in-depth batch script once that builds a MSSQL database. There are lots of great hints in that script that may help you get going.
The script is not specifically using ODBC but I do believe SQLCMD args can be changed to use a ODBC defined connection? That may work for you; and not just on MSSQL server.

Can't connect to database, error 80040e21. Impossible to debug

I have a simple file that tries to connect to a database-
<%
Set RSDiscounts = Server.CreateObject("ADODB.Recordset")
RSDiscounts.ActiveConnection = "Data Source=serverName;Initial Catalog=dbName.dbo;Integrated Security=True"
%>
When I run it, I get-
error '80040e21'
/filename.asp, line 3
Searching for the error code doesn't help. My best guess is that something is specified in the connection string that shouldn't be there. But I used Visual Studio to create the string, and that connects to the database fine.
Is there any way I can figure out what's wrong? This seems like it's impossible to debug.
I think the problem is with your connection string - the string you have there is for ADO.Net but I don't believe that will work with ADODB.
Try a connection string like this:
Driver={SQL Native Client};Server=myServerName\theInstanceName;Database=myDataBase; Trusted_Connection=Yes
Or this is a connection string from one of my old projects with ADODB (from asp classic)
Provider=SQLOLEDB.1;Initial Catalog=databaseName;Data Source=serverName;Trusted Connection=Yes
That may not be 100% right, but you can find more details of all the connection strings you could want at the excellent ConnectionStrings.com.
From the library I wrote :
function SqlServerConnectionString( byval psDataSource, byval psCatalog, byval psUid, byval psPw)
'______________________________________________________________________________
'
' 'Sql Server Connection String'
'______________________________________________________________________________
dim x
x = "Provider=MSDASQL.1;Persist Security Info=False;User ID=" & psUid & ";Data Source=" & psDataSource & ";Initial Catalog=" & psCatalog
if psPw <> "" then
x = x & ";pwd=" & psPw
end if
SqlServerConnectionString = x
end function
I have similar routines for Firebird, Odbc and Access.
The problem will be you are trying to connect to the database using the user which is running the script. If this is running in IIS it will be something like USR_.
2 alternatives.
Give this user access to the database (I wouldn't do this one).
Create a SQL user and connect via this.
PROVIDER=SQLOLEDB;Data Source=serverName;Initial Catalog=dbName.dbo;USER ID=WebUser;PASSWORD=WebUserPassword;