I cannot connect to the database in Visual Basic - database

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

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.

VB.NET SqlConnection to MySQL 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

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

Import Database (.mdf) file built in visual studio 08 into Visual Studio 12

I have worked on visual studio 08 as an undergrad and i want to start developing my then project in visual studio 12 . How can i do that ... There is no option to import .mdf files.
any help will be appreaciated.
I got the answer to the above question , i connected the data base , but how ever its gives me an error when i run the code .
I am trying to make a web application in visual basic .
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Conn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim password As String
password = Encrypt(TextBox2.Text, "&%##?,:*")
'Queries
Dim query As String = "select * from Registration where username='" & TextBox1.Text & "' and password='" & password & "'"
Dim SQLConn As New SqlConnection(Conn)
Dim SQLCmd As New SqlCommand(query, SQLConn)
SQLConn.Open()
Dim dr As SqlDataReader
dr = SQLCmd.ExecuteReader()
dr.Read()
' If Present in databse it will enter here
If dr.HasRows Then
' Remember Session
'Session("viewid") = dr("userid")
Session("userid") = dr("userid")
Session("username") = dr("username")
Session("email") = dr("email")
'Remember Me on this pc
If CheckBox1.Checked Then
Response.Cookies("UserName").Value = dr("username")
Response.Cookies("UserName").Expires = DateTime.Now.AddMonths(1)
End If
Response.Redirect("Home.aspx")
End If
SQLConn.Close()
Label4.Text = "* Incorrect Username/ Password/ Mode. Re-enter!"
End Sub
It gives me an error at SQLConn.Open():
SqlException was unhandled by user code
The user instance login flag is not allowed when connecting to a user instance of SQL Server. The connection will be closed.
Can someone tell me what need to be done ?
I suppose you try to attach your DB file on SQL Server? There was a similar problem under Windows 7, which was cause by invalid security rights when installing SQL.
The workaround was to delete a directory, which is automatically recreated if missing:
Delete C:\Documents and Settings\USERNAME\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS.
But I really don't know if it is the same cause on Win8.
Hope this helps
Serge

Resources