VB.net Receiving error BC30201: Expression expected - vb.net

Im using this to declare a connection to a SQL
Public CONN As New SqlConnection("Data Source=" & My.Settings.SrvName & ";Initial Catalog=" & My.Settings.Catalog & ";Persist Security Info=" & True & ";User ID=" & My.Settings.USER & ";Password=" & My.Settings.PASSWRD & ";Integratedsecurity=" & My.Settings.InterSec & ";Connection Timeout=" & My.Settings.CnnTimeOut &)
but on the Closing ')' Im getting the error BC30201: Expression expected, this same method Ihave use in other proyects and works, can anyone tell me where my error?, please help.
Thanks.

This is a fine example of why lots of string concatenation is a bad idea. Your code is hard to read - even for you, obviously - and so it's error prone. With all those & operators in there, you haven't noticed that you have one you don't need at the end, This:
& My.Settings.CnnTimeOut &)
should be this:
& My.Settings.CnnTimeOut)
You should avoid using multiple & operators in one line and instead use the String.Format method or string interpolation. In this case, don't use any of those options. You should be using a SqlConnectionStringBuilder, e.g.
Dim builder As New SqlConnectionStringBuilder With {.DataSource = My.Settings.SrvName,
.InitialCatalog = My.Settings.Catalog}
Using connection As New SqlConnection(builder.ConnectionString)
'...
End Using
Notice that I have created the connection with a Using statement, which is what you should be doing too. Don't use a single, common connection. You can use a single connection string builder to generate the connection string, but you should then create, use and destroy connection objects where and when you need them.
Note that you can set as many properties of the connection string builder as you need to when you create it. I have just set two here for brevity.

Related

Getting an ODBC Connection error in VB.NET when trying to connect to Teradata

First time questioner, be gentle
I'm trying to connect to a Teradata database using ODBC. When the code was originally written it worked. We have since upgraded the ODBC drivers for Teradata.
I tried connecting using VBA (Excel) as we still have some old code lying around
VBA code (simplified)
private FConnection as New ADODB.Connection
sub DBConnect(DSNName as string, UserName as string, Password as string)
Set FConnection = New ADODB.Connection
FConnection.Open DSNName, UserName, Password
This works with no issues. It also works if I use
FConnection.Open "DSN=" & DSNName & ";UID=" & UserName & ";PWD=" & Password & ";"
So I know the ODBC connection is not an issue.
Trying the same with VB.NET
Dim FConnection As Odbc.OdbcConnection
try
FConnection = New Odbc.OdbcConnection()
FConnection.ConnectionString = "DSN=" & DSNName & ";UID=" & UserName & ";PWD=" & Password & ";"
FConnection.Open()
Catch ex As Odbc.OdbcException
MessageBox.Show(ex.Message)
End Try
This results in
ERROR [08001] [Teradata][socket error] (439) WSA E HostUnreach: The Teradata server can't currently be reached over this network
I've tried a number of variations on the Connection string but nothing.
EDIT: I tried using Teradata.net instead of ODBC, but all variations of that end up with a Socket Exception in System.Net.Dns.GetAddrInfo
Pinging the server name works without issue

SSL connection string for Azure PostgreSQL - correct syntax

I have a Microsoft Excel workbook which I connect to a PostgreSQL db. I have had this working with the db on localhost for some time.
I have now moved my db to Azure PostgreSQL. I have successfully reconfigured my queries/connections to pull data into the spreadsheet (by setting up a DSN in 'ODBC Data sources 64 bit') with SSL set to require.
The workbook includes some vba to write data back to the database. I am getting the error:
Runtime error: '-2147467259 (80004005)': FATAL: SSL connection is
required. Please specify SSL options and retry.
The error throws on the dbConnPublic.Open sqlConnString line
The relevant parts of the code look like this:
Sub WriteRowToDB()
' Define connectivity
Dim dbConnPublic As New ADODB.Connection
Dim sqlConnString As String
sqlConnString = OpenConnection()
dbConnPublic.Open sqlConnString
End Sub
Public Function OpenConnection() As String
'Define connection objects and terms
Dim sqlConnString As String
Dim myDriver As String: myDriver = "{PostgreSQL ANSI(x64)}"
Dim myServer As String: myServer = "djm-main-01.postgres.database.azure.com"
Dim myDatabase As String: myDatabase = "postgres"
Dim myUserName As String: myUserName = "djmmain01admin#djm-main-01"
Dim myPassword As String: myPassword = "[my password]" ' this replaced by the real password
' Open connection
sqlConnString = "Driver={PostgreSQL ANSI(x64)};" & _
"DSN=postgres;" & _
"Server=" & myServer & ";" & _
"Port=5432;" & _
"UID=" & myUserName & ";" & _
"PWD=" & myPassword & ";" & _
"Database=" & myDatabase & ";" & _
"ssl=true;READONLY=0;PROTOCOL=6.4;FAKEOIDINDEX=0;SHOWOIDCOLUMN=0;ROWVERSIONING=0;SHOWSYSTEMTABLES=1"
OpenConnection = sqlConnString
End Function
I have tried every combination of ssl=true, ssl=required, sslmode=required, using two parameters and three, some with caps, some lowercase, some mixed. cannot find anything that makes a difference. Also not sure if this syntax is Azure, PostgreSQL or ADODB.
Note that I can also successfully connect to the Azure db using DBeaver and command line psql from Windows, using SSL.
Hi anyone who is watching. So I worked this out.
Actually very simple, the required parameter is ssmode=require. It is case sensitive. I must have somehow missed this from my permutations. And therefore assume that the syntax is determined by the PostgreSQL ODBC driver.
This resource helped:
https://www.connectionstrings.com/
Additional gotcha to watch out for : when the password is included in the connection string, then any non-alphanumerics need to be url encoded which I wasn't thinking about,so my system generated password with an exclamation mark had to be converted to %21. I got the encoded password from the User DSN at HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\
However I have now changed the password so that it does not use non-alphanumerics.
Hope this is useful.

Input username and password for SQL Server from userform VBA Excel

I want to input username and password SQL Server from userform VBA Excel, but I don't understand how to do that. So I create code like this:
Sub OPenCOnn()
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID=" & txtUser.Text & ";Password=" & txtPass.Text & ";"
End Sub
But its didn't work. I receive the below error:
run time error, object required
You need single quotes around the strings like this:
cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID='" & txtUser.Text & "';Password='" & txtPass.Text & "';"
run time error, object required
You are getting that error because your code cannot find txtUser and txtPass
Ensure the textboxes are there.
Use Option Explicit on the top of your code and then you will notice that it will highlight txtUser and say that Variable not defined. Of Course you will have to also define cnn as Dim cnn As ADODB.Connection

Unhandled Exception of Type System.Data.SqlClient SQL Exception in System.Data.dll

I am attempting to code a little Customer/sales database in VB. However on compiling I am getting the error stated in the subject. Apparently there is no connection to the database posible.
Here is the code I got so far:
Public Class Principal
Using Connect As SqlConnection =
Friend Sub CreateDatabase()
New SqlConnection("Data Source=(local);" &
"Integrated Security='SSPI';")
Dim strCreateDatabase As String = "IF EXISTS ( " &
"SELECT name " &
"FROM sys.databases " &
"WHERE name = N'BMSTIDB'" &
" ) " &
"DROP DATABASE BMSTIDB; " &
"CREATE DATABASE BMSTIDB"
Dim Command As SqlCommand =
New SqlCommand(strCreateDatabase, Connect)
Connect.Open()
Connect.ExecuteNonQuery()
MsgBox("A Database with the name of " &
"BMSTIDB has been created. ")
End Using
It compiles fine and it doens't display any errors or issues. However as mentioned above it does give the error upon running, when it first attempts to connect to the DB.
I am using Visual Studio 2015 Enterprise and Community.
Thanks a lot,
BenjB
New SqlConnection("Data Source=(local);" &
"Integrated Security='SSPI';Database=master")
You're missing a closing single quote here:
"WHERE name = N'BMSTIDB" &
It should be:
"WHERE name = N'BMSTIDB'" &
Once you fix that you'll find you're also missing the BEGIN and END keywords.

VB.NET Linq to SQL - Query from table

I am starting with Linq to SQL in VB.NET, and trying to figure out how to make a simple query to a database.
I want to do it all programaticly.
I have made a connection to the database with a connectionstring, and this works fine - I can get a message if the database exists or not.
But when I want to query a table, I am missing the part where I connest to the table. I have googled a lot to find an answer for thi, but
no luck. Can anyone point me in the right direction?
Code:
Dim strContactString, strDBServer, strDBName, strSQLUser, strSQLPW As String
strDBServer = "MyServer"
strDBName = "Northwind"
strSQLUser = "sa"
strSQLPW = "MyPW"
strContactString = ""
strContactString = strContactString & "data source=" & strDBServer & ";"
strContactString = strContactString & "initial catalog=" & strDBName & ";"
strContactString = strContactString & "user id=" & strSQLUser & ";"
strContactString = strContactString & "password=" & strSQLPW & ";"
Dim MyContext As New DataContext(strContactString)
'This works:
If MyContext.DatabaseExists Then
MsgBox("DB Exists")
Else
MsgBox("DB Does Not Exist")
End If
'This is the query I want to run (copied from samples I found)
Dim TEST = From c In MyContext.Customers _
Select c.ContactName
Error message:
'Customers' is not a member of 'System.Data.Linq.DataContext'.
First off you're not supposed to use DataContext directly.
You add a new dbml file to your project and map that to the database using the editor (this means connecting visual studio to your database, then dragging the tables you want from the server explorer to the dbml editor).
That will generate for you a class colled something like NortwindDataContext (you can control this from the properties pane in the editor).
You can then use that to write your queries:
Dim context As New DataContext(strContactString)
Dim TEST = From c In context.Customers _
Select c.ContactName
http://msdn.microsoft.com/en-us/library/bb399375.aspx
"Best practice is to declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example."
As long as the db is connected correctly, this may be your problem.