VB.NET SqlConnection to MySQL Database - database

although I did read plenty of stackoverflow posts and also checked out lots of tutorial websites I can't get my code to work.
I want to use sqlBulkCopy. And therefor I need a instance of the 'SqlConnection' class. I have a MySQL Database running and I have no problem at all opening a connection with the 'MySqlConnection' class.
I have tried several approaches to get SqlConnection working.
MySqlConnection (works):
Dim a = "Server=localhost;Initial Catalog=hauptdatenbank;User Id=johnny;Password=123456;"
Using cn As New MySqlConnection(a)
cn.Open()
End Using
SqlConnection (does not work):
Dim a = "Server=localhost;Initial Catalog=hauptdatenbank;User Id=johnny;Password=123456;"
Using cn As New SqlConnection(a)
cn.Open()
End Using
Following SqlException gets thrown:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)

SqlBulk is only for a SQL DB.
MySqlBulkLoader is for a MySQL DB.
Thanks for the comments!

Imports MySql.Data.MySqlClient
Module Connection
Public str1 As String = "data source=localhost;user id= root;password=;database= parisbugdb;"
End Module
If Len(Trim(PassBox.Text)) = 0 Then
AlertLabel.Visible = True
AlertLabel.Text = "Password required!"
PassBox.SelectAll()
PassBox.Focus()
Return
End If
con.Open()
Dim Sql = "SELECT * FROM userx WHERE username ='" & UserBox.Text & "' AND password = '" & PassBox.Text & "'"
scmd = New MySqlCommand(sql, con)
Dim sdr As MySqlDataReader = scmd.ExecuteReader
Try
If sdr.Read = False Then
AlertLabel.Visible = True
AlertLabel.Text = "Login denied!"
con.Close()
Else
UserBox.Clear()
PassBox.Clear()
UserBox.Focus()
Me.Hide()
Dashboard.Show()
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub

Related

how to connect VBScript (Excel) to SQL Server web database (via IP)

I'm at my job trying to do some unknow stuff for me, you see, we're trying to connect an excel document with a VBScript Macro to a databse stored in web server but for some reason doesn't recognizes the user and throws an error repeatedly, i discarded a connection issue since it returns an SQL error instead of something like a timeout or server doesn't exists or something like that, we're trying to connect to the server using the ip address, we also checked that the logging method is on mixed (win and sql) and remotes connections to the server are enabled as well, also if i use the credentials provided in the connection string (username and password) i can actually log in to SQL Server without any issue, we also tried a direct connection (external vpn) because we thought it could be our firewall, but got the same error anyway, so we have no clue what it could be and we're kinda running out of ideas on how to do this, i'll post down below the code i'm using to trying the connection (obviously test data but similar to reality)
picture of the error i'm getting (don't post the original since it's in spanish but is very similar to this):
code i'm currently trying:
Sub excel_sqlsrv()
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
strConn = "Driver={ODBC Driver 17 for SQL Server};Server=10.20.30.5;Database=mydb;UID=sa;PWD=abcd12345;"
conn.Open strConn
strSqL = "SELECT * FROM USERS"
rs.Open strSqL
End Sub
Any advice, tip or trick could be of tremendous help for me, i'll be looking forward to any kind of comment, thanks in advance
Use the ODBC Data Source Administrator to create a connection named mydb and test it works. Then use
Sub excel_sqlsrv()
Const strConn = "mydb" ' ODBC source
Const strsql = "SELECT * FROM USERS"
Dim conn As Object, rs As Object
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open strConn
If conn.Errors.Count > 0 Then
Dim i, s
For i = 0 To conn.Errors.Count - 1
s = s & conn.Errors(i) & vbLf
Next
MsgBox s
Else
On Error GoTo 0
Set rs = conn.Execute(strsql)
Sheet1.Range("A1").CopyFromRecordset rs
End If
End Sub
You can try using OLEDB provider instead of ADODB.

How to secure connection between Vb6 application and mssql server?

I am working on a legacy application which uses sqloledb provider and activex data objects to connect to mssql database. Now I need to encrypt the connection between the application and server without force encryption option in sql server.
I have installed a self signed certificate in the sql server instance and tried putting the Encrypt=true and Trustservercertificate=true in connection string. But the connection is not encrypted.
I have tried using ODBC provider with ADO and while using encrypt=true and trustservercertificate=true, I am getting a SSL security error which opening the connection.
Please let me know how to establish a secure connection using ADO 2.8 library.
Private Sub Command1_Click()
Dim sConnectionString As String
Dim strSQLStmt As String
'-- Build the connection string
'sConnectionString = "UID=userid;PWD=password;Initial Catalog=EHSC_SYM_Kings_Development;Server=EHILP-257\MIB14;Provider=MSOLEDBSQL;Encrypt=YES;trustServerCertificate=YES"
'sConnectionString = "Provider=sqloledb;Data Source=192.168.27.91\MIB14;Initial Catalog=EHSC_SYM_Kings_Development;User Id=userid;Password=password;Encrypt=YES;trustServerCertificate=YES"
'sConnectionString = "driver={SQL Server};server=192.168.27.91\MIB14;user id=userid;password=password;Initial Catalog=EHSC_SYM_Kings_Development;Encrypt=Yes;trustServerCertificate=True"
sConnectionString = "Provider=SQLNCLI11;Server=192.168.27.91\MIB14;Database=EHSC_SYM_Kings_Development;Uid=userid;Pwd=password;Encrypt=yes;trustServerCertificate=True"
strSQLStmt = "select * from dbo.patient where pat_pid = '1001'"
'DB WORK
Dim db As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim result As String
db.ConnectionString = sConnectionString
db.Open 'open connection
With cmd
.ActiveConnection = db
.CommandText = strSQLStmt
.CommandType = adCmdText
End With
With rs
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmd
End With
If rs.EOF = False Then
rs.MoveFirst
Let result = rs.Fields(0)
End If
'close conns
rs.Close
db.Close
Set db = Nothing
Set cmd = Nothing
Set rs = Nothing
End Sub
Thank you all for your suggestions, I finally managed to make the connection secure by changing the driver to sqlserver native client 11(ODBC). Looks like sqloledb doesn't have support for tls. Changing the driver to ODBC doesn't seem to change the behaviour much. Rest of my code works fine without any changes
sConnectionString = "Driver={SQL Server Native Client 11.0};Server=192.168.27.91\MIB14;Database=xxxxxxxx;user id=xxxxxxx;password=xxxxxxxxx;Encrypt=yes;TrustServerCertificate=yes"
Just went through this myself.
For your original connection string the keyword you're looking for is not "Encrypt=true" or "Encrypt=yes" like most of the internet would lead you to believe. It's "Use Encryption for Data=true".
So your connection string becomes:
sConnectionString = "Provider=SQLNCLI11;Server=192.168.27.91\MIB14;Database=EHSC_SYM_Kings_Development;Uid=userid;Pwd=password;Use Encryption for Data=true;trustServerCertificate=True"
The trustservercertificate=true is just for testing with self-signed certs... and exposing yourself to man-in-the-middle attacks ;)
For reference this was tested with:
VB6 connecting to SQL Server 2016 using SQLNCLI11 provider via ADODB.

Error connecting to SQL Server 2012 with VB.NET 2010

I have been trying to fix a project which already use a 100% connections to Oracle. They are trying to upgrade the project to start using SQL Server 2012 Management Studio. But I'm having issues connecting to the database. We use Windows authentication.
I can login fine directly to SQL Server 2012 using Management Studio and Windows authentication. If I create a fresh new WindowsApplication1 project to test the connection code it works fine, I'm using this code (and get an error is at conn.Open()):
Imports System.Data.SqlClient
Public Class Open_Filing_Image
'Create ADO.NET objects.
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private results As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Create a Connection object.
Dim connStr As [String] = "Server=servername; Database=dbname; Integrated Security=True"
myConn = New SqlConnection(connStr)
'Create a Command object.
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT DdocName FROM dbo.Document WHERE XAlaskaID = '72010' and DdocType = 'Filings'"
'Open the connection.
Try
myConn.Open()
MsgBox("Connection Open ! ")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
myReader = myCmd.ExecuteReader()
'Concatenate the query result into a string.
Do While myReader.Read()
results = myReader.GetValue(0)
Loop
'Display results.
Dim documentID As String = results
Dim outPath As String = "http://address.internet`enter code here`/" + documentID + (".pdf")
System.Diagnostics.Process.Start(outPath)
'Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
Error message:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The specified data could not be decrypted.
Thank you.
Fix it doing some research and some assistance by another programmer:
The project had a Bcrypt reference that block the connections to SQL. I delete all Bcrypt and add transport credentials to Windows in the app.config. any way thanks guys.

Visual Studio 2010 - cannot reconnect to SQL Server instance after project is saved

Using Visual Studio 2010 I am able to start a new project using ADODB (Microsoft ActiveX Data Objects 6.1 Library COM 6.1.0.0) to connect to MS Access and SQL Server, save the project, re-open the project and it all works as expected. BUT when I do this trying to connect to a SQL Server Instance it will work until I save the project after which I always get the error: "SQL Server does not exist or access denied".
Here is the code for my test console application;
Module Module1
Sub Main()
Dim cn As New ADODB.Connection()
Dim rs As New ADODB.Recordset()
Dim cnStr As String
' Modify this connection string to reflect your server and logon information.
' Store the connection to a variable to be used throughout this example.
cnStr = "Provider=SQLOLEDB;Initial Catalog=Firehouse;Data Source=devclstr\devclstr;" & _
"User ID=xxx;Password=xxx;"
' 1. Connect through the Connectionstring property.
cn.ConnectionString = cnStr
cn.Open()
rs.Open("select * from usr_sec", cn)
Dim da As New System.Data.OleDb.OleDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write("There are " & ds.Tables(0).Rows.Count.ToString & " total users.")
Console.ReadLine()
rs = Nothing
cn.Close()
cn = Nothing
End Sub
End Module
This will work only in the following scenario: start new console project, enter the code, add the "ActiveX Data Objects 6.1 Library" reference, and it runs as expected. As soon as I save it each subsequent execution gives me the following error:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2147467259
HResult=-2147467259
Message=[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
Source=Microsoft OLE DB Provider for SQL Server
StackTrace: at ADODB._Connection.Open(String ConnectionString, String UserID, String Password, Int32 Options)
Please share any insight in how to resolve this problem
Normally, I'd advise against using the COM approach, when there are built in connectors, so instead, something like:
Imports System.Data.SqlClient;
Module Module1
Sub Main()
' Modify this connection string to reflect your server and logon information.
Dim cnStr As String = "Initial Catalog=Firehouse;Data Source=devclstr\devclstr;User ID=xxx;Password=xxx;"
Using con as New SqlConnection(cnStr)
con.Open()
Using cmd as New SqlCommand("select * from usr_sec", con)
Using da As New SqlDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write(String.Format("There are {0} total users.", ds.Tables(0).Rows.Count))
Console.ReadLine()
End Using
End Using
End Using
End Sub
End Module

I cannot connect to the database in Visual Basic

I have the following code:
Dim string_conectare As String = "Data Source=|DataDirectory|\Database1.sdf"
Dim conexiune As SqlConnection
conexiune = New SqlConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
As you can see i would like to open a connection to the database but every time I want test it I get this error:
A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is
configured to allow remote connections. (provider: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)
I struggled for more than 2 hours, so please help me!
Later edit:
I've tried this:
Dim string_conectare As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database1.sdf;Persist Security Info=True"
Dim conexiune As OleDbConnection
conexiune = New OleDbConnection(string_conectare)
conexiune.Open()
If conexiune.State = ConnectionState.Open Then
MsgBox("OK")
Else
MsgBox("not ok")
End If
but it throw me this error:
Unrecognized database format
Here is an excerpt of the same code I use to connect to my databases:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
Try that.
Be sure to add the resource MySQL.Data into your project and also call it using:
Imports MySQL.Data.MySQLClient
ALSO! Be certain that when you created the database that you enabled external database access. If you don't do that then VB programs will not be able to access it and it will limit access to your webhost only.
The Jet OLEDB Provider is for Access databases. It can't handle sdf files. Try with the correct connection string.
You can take help of this website to get the correct connection string for your database:
www.ConnectionStrings.com
Is the application built on shared storage and you are trying to run it from local machine?
That could be an issue if the server containing the app does not have access to db

Resources