how to open database connection in 1 form then close it in another form? - vb.net

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.

Related

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

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 ?

How to represent currently logged in user in vb.net

I am in desperate need of some help.
I'm using SQL Server and vb.net. On my personal info Windows form I'm trying to populate textboxes with user information based on the currently logged in user.
However I don't know how to represent the value of the current user. I'm trying to pass the value as a parameter. What should be put in place of: #idontknow ?
Code for form:
Private Sub PersonalInfo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim dt As New DataTable
connection.Open()
Dim sqlcmd As New SqlCommand("SELECT * FROM PATIENT WHERE PATIENT_ID = #id", connection)
Dim sqlda As New SqlDataAdapter(sqlcmd)
Dim user_email As Object = Nothing
sqlcmd.Parameters.AddWithValue("#id", #idontknow)
Dim reader As SqlDataReader = sqlcmd.ExecuteReader()
While reader.Read()
fname.Text = reader("PATIENT_FNAME")
ComboBox1.Text = reader("patient_gender")
TextBox4.Text = reader("patient_street")
TextBox5.Text = reader("patient_city")
TextBox6.Text = reader("patient_state")
TextBox7.Text = reader("patient_zip")
TextBox8.Text = reader("patient_phone")
email.Text = reader("user_email")
End While
End Sub
Here I validate User credentials on a windows form by checking email and password, the primary key (patient_id) is generated upon insert when a new user registers (this code is on a separate form, which is not displayed below):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim command As New SqlCommand("select * from patient where user_email = #email and user_pass = #pass", connection)
command.Parameters.Add("#email", SqlDbType.VarChar).Value = email.Text
command.Parameters.Add("#pass", SqlDbType.VarChar).Value = pass.Text
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show(" Username or Password are Invalid")
Else
MessageBox.Show("Login Successful")
command.CommandType = CommandType.StoredProcedure
dashboard.Show()
End If
End Sub
Your login code queries for a record from the patient table that has the appropriate username and password. Right now it looks like all you're doing is checking for the existence of such a record. What you want to do is take that record's patient_id and store it somewhere that you can refer back to from elsewhere in your code. This could be something as simple as a shared property somewhere. This question discusses a few options that might suit. For instance, a module:
Module CurrentUser
Public Property PatientId As Integer
End Module
Or a class that can't be instantiated:
NotInheritable Class CurrentUser
Private Sub New()
End Sub
Public Shared Property PatientId As Integer
End Class
Review the answers to the question linked above for a discussion of the differences between the two approaches. In either case, you'd assign the value of CurrentUser.PatientId in your login code and then access its value where you've written #idontknow.
One last thing: it looks like your login code is taking the contents of a password box somewhere and comparing it directly to the contents of the password field in your database, which strongly implies that you're storing passwords as plain text. This is not secure. Review this question for a thorough overview of how to store passwords securely.
Well, I'm not sure if you're looking for a logged user in Windows, then it's a string (not Integer) as follows:
Dim UserNameStr As String = Environment.UserName
Same applies to the SQL Server:
SELECT CURRENT_USER;
...it's a string too.

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

How do I transfer data from Text Boxes in a form to an Access Table

I'm currently trying to write code for a form that has text boxes for a user to input the required data into which then with the use of button the data in the text boxes will be sent to an access table.
If you need any more information to help solve the problem I'm willing to provide it if you ask (I would upload pictures/screenshots but I need "10 reputation" apparently.
You can do this
Imports System.Data.OleDb
Public Class Form1
Dim AccessConection As OleDbConnection
Private Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
Dim cmd As New OleDbCommand
Dim mySql As String
mySql = "INSERT INTO Customs (CustomName,Address) VALUES(#Name,#Address)"
Try
cmd.Parameters.AddWithValue("#Name", txName.Text)
cmd.Parameters.AddWithValue("#Address", txAddress.Text)
cmd.Connection = AccessConection
cmd.CommandType = CommandType.Text
cmd.CommandText = mySql
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Whatever you want to say..." & vbCrLf & ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myDataBasePath As String = "C:\Users\user\Source\Workspaces\......\SOF003\Data.accdb" 'Here you put the full name of the database file (including path)
'The next line is for Access 2003 .mdb files
'Dim CadenaConection As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", myDataBasePath)
Dim CadenaConection As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", myDataBasePath)
AccessConection = New OleDbConnection(CadenaConection)
AccessConection.open()
End Sub
End Class
btSave is the command button.
Customs is the table's name.
CustomName and Address are two fields.
txName and txAddress are two TextBox Control.
Obviously you should be careful with the data types (here I use only strings), validation, etc, etc... But, this is a starting point. If you search, you'll find another ways, more elaborated.

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.