Connection string problem connecting to local SQL database using VB.NET in Visual Studio - sql

I can't understand why I can't connect with my SQL Server Express LocalDB. I keep getting in to trouble with my connection string. This is what I have tried:
Imports System.Data.OleDb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conString As String 'Connection string
Dim con As OleDbConnection 'Connecting to your database
Dim Command As OleDbCommand 'Query "What do you want in the database"
'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=SQLOLEDB; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=System.Data.SqlClient; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
Try
con = New OleDbConnection(conString)
con.Open()
Command = New OleDbCommand("select * from LogInTable where UserID = ? and Password = ?", con)
Dim parm1 As OleDbParameter, parm2 As OleDbParameter
parm1 = Command.Parameters.Add("#UserID", OleDbType.VarChar)
parm2 = Command.Parameters.Add("#Password", OleDbType.VarChar)
parm1.Direction = ParameterDirection.Input
parm2.Direction = ParameterDirection.Input
parm1.Value = Me.TextBox1.Text
parm2.Value = Me.TextBox2.Text
Command.Connection.Open()
Dim reader As OleDbDataReader
If reader.Read = True Then
Me.DialogResult = DialogResult.OK
Else
MsgBox("Invalid UserID or Password")
End If
reader = Command.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I have tried several connection strings, but none is working.
But with the number 4, I got error
Multiple-step OLE DB operation generated errors.check each OLE DB status value
The others results in an error:
provider not recognized
My other attempt was with SqlClient:
Imports System.Data.SqlClient
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=localhost;Integrated Security=SSPI;")
'"Data Source = (LocalDB) \ MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True")
' "Data Source=localhost;Integrated Security=SSPI;")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
My error here was:
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while connecting to SQL Server. The server was not found or was not available. Verify that the instance name is correct and that SQL Server is configured to accept external connections. (provider: Named Pipes Provider, error: 40 - Unable to open a connection to SQL Server)
I have one table in my SQL Server database with two columns UserID and password.
I would be very grateful if someone could point me in the right direction here. I have read many post on the subject but cant seem to find where I go wrong. My main goal here is to connect with my database.

As you are new you can try some visual tools it can help you to see more clear, I suggest you to try this approach, it's a half way to your solution :
In your visual Studio :
Menu Tools
Connection to database
In the Dialog
Data Source : Microsoft SQL Server (sqlClient)
Server Name : ****
you should find your server here, select it, Else that's mean you have problem with your server installation
Authentification : Windows Authentification
as i see in your example your are not using SQL id so that's fine
Connection to database:
Select the Database that you already created, if nothing seen
that's mean you didn't created or you don't have rights to access
Then Click in button Test Connection
if success then click OK
Then go to your ToolBox
Data
DataGridView drop it in your form
select data source : in bottom you will see + Add the data source
click on it
You will have a Dialog, choose Database -> Dataset ->
choose you data connection
you should see a line in the combobox with your server name \ your Database.dbo
Check in the checkbox "Show the connection string saved in the application"
you will see clearly your connection string
Next -> Next > check Tables
Finish
If you stuck in some part let me know to clarify you by an Edit

First of all, THANK YOU :), I got it to work. But I still have som questions.
I started with a fresh project and made a local sqlDB with one table
with two columbs "UserID" and "Password".
I had one line in this table with "Admin" and "pass"
I did not use the table designer or add a datasource.
I followed your description to the letter and copied my connectionstring under tool connect...
That worked fine and I found the mdf file and was able to connect to it
Loaded the form with a datagrid and bound it to the datasource. It worked properly
Then I tried to connect to the DB under a new button manualy. I got this error message:
System.Data.SqlClient.SqlException:
'Cannot attach file 'C:\Users\Bruker\source\repos\Connect_v2\Connect_v2\bin\Debug\Database1.mdf'
as database 'OutComes
' because this file is already in use for database
'C:\USERS\BRUKER\SOURCE\REPOS\CONNECT_V2\CONNECT_V2\BIN\DEBUG\DATABASE1.MDF''
This was the class:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
I tried to comment out the load event and It connected with the DB manualy. It worked :)
Imports System.Data.SqlClient
Public Class Form1
'Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
' Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)
'End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
This is great but I still wonder why I got the error message. Is it because the datagridview tableadapter holds a constanctly open connection to the DB. And is not possible to have multiple open connections at the same time ?

Related

How to link to a relational database - visual basic

I am creating a flashcard application where each user can create flashcards which will be specific to them. I was wondering how I can link each flashcard they create to their specific account.
Imports System.Data.OleDb
Public Class CreateFlashcards
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into Flashcards ([Front],[Back]) values ('" & txtFront.Text & "','" & txtBack.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(txtFront.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(txtBack.Text, String)))
MsgBox("You have successfully added the flashcard into your deck!")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtFront.Clear()
txtBack.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This works in that it adds the data into the access database but it does not link to the users account. I have also linked the tables in access
The login table
The flashcard table
As you can see the loginID key does not link
Normally, the connection string for Access contains the the path to the database file for the Data Source attribute.
You will need to add a field to your Flashcard table to hold the UserID. This will tie the 2 tables together.
Database objects like connections and commands need to be disposed as well as closed. Using...End Using blocks handle this for you even if have an error. In this code you both the connection and the command are included in the same Using block.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the sql command text and the connection to the constructor of the command.
When you are using parameters, which you should in Access and Sql Service, put the name of the parameter in the sql command text. It is not necessary to convert the Text property of a TextBox to a string. It is already a String.
I had to guess at the OleDbType for the parameters. Check your database. It is important to note that the order that parameters appear in the sql command text must match the order that they are added to the parameters collection. Access does not consider the name of the parameter, only the position.
I assume you can retrieve the user's ID when they log in to create flash cards. When the user logs in to use there flash cards you would do something like Select * From Flashcards Where LoginID = #UserID;.
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
Try
InsertFlashcard()
MsgBox("You have successfully added the flashcard into your deck!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub InsertFlashcard()
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Dim Command = " insert into Flashcards (LoginID, [Front],[Back]) values (#Id, #Front, #Back);"
Using myconnection As New OleDbConnection(pro),
cmd As New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserID", OleDbType.Integer).Value = ID
cmd.Parameters.Add("#Front", OleDbType.VarChar).Value = txtFront.Text
cmd.Parameters.Add("#Back", OleDbType.VarChar).Value = txtBack.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
EDIT
As per comment by ADyson I have added code to retrieve ID. Of course in your real application you would be salting and hashing the password. Passwords should never be stored as plain text.
Private ID As Integer
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Using cn As New OleDbConnection(pro),
cmd As New OleDbCommand("Select LoginID From login Where Username = #Username and Password = #Password;")
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = txtUserName.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Text
cn.Open()
Dim result = cmd.ExecuteScalar
If Not result Is Nothing Then
ID = CInt(result)
Else
MessageBox.Show("Invalid Login")
End If
End Using
End Sub

Login always fails in my Sql based visual basic simple login application

I tried to create a login page in VISUAL BASIC. But the problem is that the login always fails . My program is connected to my sql database and though my password and username is correct through text boxes the output is always login fail!! and I don't know where is screwed up .
Imports System.Data.SqlClient
Public Class login
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection1 As New SqlConnection With {.ConnectionString = "Server = VAIOO-PC ; Database = forum ; Integrated Security= true "}
Dim sqlcommand As New SqlCommand(" Select * from username where username= #username and password =#password", connection1)
sqlcommand.Parameters.Add("#username", SqlDbType.VarChar).Value = textboxuser.Text
sqlcommand.Parameters.Add("#password", SqlDbType.VarChar).Value = textboxpassword.Text
Dim sqldtaadpt As New SqlDataAdapter(sqlcommand) 'passes the command to via the adapter
Dim table As New DataTable()
If table.Rows.Count() <= 0 Then
MsgBox("USERNAME or THE PASSWORD IS INCORRECT")
Else
MsgBox("login successful")
End If
End Sub
End Class
You forgot to fill the datatable.
Use Fill method of DataAdapter.
sqlcommand.Open()
sqldtaadpt.Fill(table)
To get a full example, look at SqlCommand class help.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

VB.Net - Inserting data to Access Database using OleDb

Can you please tell me what's wrong with the code I'm using? Everytime I execute this, it throws the exception (Failed to connect to database)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb"
Dim sql As String = String.Format("INSERT INTO login VALUES('{username}','{password}','{secques}','{secans}')", txt_username.Text, txt_passwd.Text, txt_secquestion.Text, txt_secansw.Text)
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim icount As Integer = sqlCom.ExecuteNonQuery
MessageBox.Show(icount)
MessageBox.Show("Successfully registered..", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
cmd_submit2_Click(sender, e)
End If
End Sub
I am using Access 2013 and VS 2015 Community, if that helps. Thank you.
You should use a parameterized approach to your commands.
A parameterized query removes the possibility of Sql Injection and you will not get errors if your string values are not correctly formatted.
Note that if you don't do anything in the exception block then it is better to remove it and let the exception show itself or at least show the Exception.Message value, so you are informed of the actual error.
Finally every disposable object should be created with the Using statement that ensures a proper close and dispose of such objects (in particular the OleDbConnection)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sql As String = "INSERT INTO login VALUES(#name, #pass, #sec, #sw)"
Using conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb")
Using sqlCom = New System.Data.OleDb.OleDbCommand(sql, conn)
conn.Open()
sqlCom.Parameters.Add("#name", OleDbType.VarWChar).Value = txt_username.Text
sqlCom.Parameters.Add("#pass", OleDbType.VarWChar).Value = txt_passwd.Text
sqlCom.Parameters.Add("#sec", OleDbType.VarWChar).Value = txt_secquestion.Text
sqlCom.Parameters.Add("#sw", OleDbType.VarWChar).Value = txt_secansw.Text
Dim icount As Integer = sqlCom.ExecuteNonQuery
End Using
End Using
End Sub
Keep in mind that omitting the field names in the INSERT INTO statement requires that you provide values for every field present in the login table and in the exact order expected by the table (So it is better to insert the field names)
For example, if your table has only the 4 known fields:
Dim sql As String = "INSERT INTO login (username, userpass, secfield, secfieldsw) " & _
"VALUES(#name, #pass, #sec, #sw)"

how to open database connection in 1 form then close it in another form?

Public Class Login
Private Shared con As New OleDb.OleDbConnection
Dim sql As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text <> "fcf#gmail.com" Or TextBox2.Text <> "fcf1234567" Then
MsgBox("Wrong username or password!! Please try again!!", 0, "!!!")
Else
con.Open()
sql = "SELECT * FROM c_info"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "c_information")
Me.Hide()
Home.Label6.Show()
Home.Label6.Text = ds.Tables("c_information").Rows(0).Item(0)
Home.Button8.Show()
Home.Button6.Hide()
Home.Button9.Show()
Profile.Enabled = True
Profile.TextBox1.Text = ds.Tables("c_information").Rows(0).Item(0)
Profile.TextBox2.Text = ds.Tables("c_information").Rows(0).Item(1)
Profile.TextBox3.Text = ds.Tables("c_information").Rows(0).Item(2)
Profile.TextBox4.Text = ds.Tables("c_information").Rows(0).Item(3)
Profile.TextBox5.Text = ds.Tables("c_information").Rows(0).Item(4)
Profile.ComboBox1.Text = ds.Tables("c_information").Rows(0).Item(5)
End If
End Sub
I'm doing a log-in system, try to open database connection then close it in another form, no idea how to do it...in this code i have typed con.open(), but when i run it twice, it says "current connection still open"
3 Suggestions:
(Less recomendable) Change con to Public Shared or Protected Shared (preferable to have it on a separate class/module); this way you'll be able to access it from all your forms and clases
(Most adecuate to your scenario) Add a property on your 2nd form of OleDb.OleDbConnection or a parameter on its constructor and pass it from Form1 when you create the second form.
(Most recommended) Rethink your design and logic. Having an open database connection wandering over all your program is a bad idea for many reasons. Create a database connection on every form/class you need one, open and close it as soon as you use it.

Select commannd in Visual Basic not working properly

I am new to Visual Basic for Applications. I have a login system in my current program. You will understand the system by reading below. I have an Access database whose table looks like following :-
Name : Cookies
----------------------------
ID | Nme | Val |
----------------------------
The table is cleared and all the contents of it is deleted when the form is closed. Now, when a user signs in, a row is added :-
----------------------------
(id) | "user" | username |
----------------------------
Now, the user enters his id and password in the form index.vb and the command to add the row in the access database is also there in the index.vb file. After the row is added, the index.vb file is hidden and the file userpage.vb is shown. Now, I have seen this that when the user logs in, the row is added properly in the access file (by refreshing the access file manually) and everything is deleted properly in the table when the window is closed. So, there is no problem in inserting and deletion of rows. So, obviously, the problem is with the displaying part. My code for displaying the username is as follows (the code is in the userpage.vb file) :-
Dim Username As String = ""
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Software\db.accdb")
Conn.Open()
Dim Cmd As New OleDb.OleDbCommand("Select Val From Cookies Where Nme='user'", Conn)
Dim Reader = Cmd.ExecuteReader
Do While Reader.Read
Username = Reader.Item("Val")
Loop
Label1.Text = "Welcome " & Username
Conn.Close()
The output that is given is "Welcome" and Username is "" even when the row has been added. Now, I have also seen this by experimenting that when I manually add a row in the access database with the same details that is going to be added in the database problematically, the program works fine. Any help, of course, will be appreciated and thanks for reading this long post.
UPDATE 1 ( as suggested by #Dimple)
My code for insertion is as follows(This code is in the index.vb page) :-
Dim usernameinput As String = TextBox1.Text
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Dim Userpage As New User_page
Me.Hide()
Userpage.Show()
You said that Access displays row after manually refreshing Access file (database). Sometimes you need to Requery() the database after insertion. I had this problem while working with Access.
Form1
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\db.accdb")
Conn.Open()
Dim usernameinput As String = "TextBox3.Text"
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Conn.Close()
Me.Hide()
Form2.Show()
End Sub
End Class
Form2
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\db.accdb")
Conn.Open()
Dim usernameinput As String = "TextBox3.Text"
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Conn.Close()
Me.Hide()
Form2.Show()
End Sub
End Class
I didnt even change the variables you named. Just avoided form designing by using msgbox.
My brother instead of using,
Do While Reader.Read
Username = Reader.Item("Val")
Loop
try
Do While Reader.Read = True
Username = Reader.Item(0)
Loop
Let me Know if it works for you.