How to read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms? - sql

This is my first question, by the way - and I'm not sure exactly how to ask, or say what's wrong. There's 3 things I can't sort so any help would be appreciated.
Module:
This and the first (login) form work as they are but I couldn't get either Form to reference con.connectionstring for them to use without having to re-use the string contained in "" (as they do below) - my attempts ended up with errors including saying that the state couldn't be changed as the connection was already open, but I'd like the same one string to be referenced from the Forms.
Module ConnectionModule
Public con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Public da As OleDb.OleDbDataAdapter
Public ds As DataSet = New DataSet
Public Path As String = Application.StartupPath
Public Sub OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
con.Open()
If con.State = ConnectionState.Closed Then
MsgBox("Connection to db not made.")
End If
End Sub
Public CurrentUser As String = Nothing
End Module
The First Form:
Public Class LoginForm
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OpenDb()
con.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ID As String = txtID.Text
Dim Pass As String = txtPassword.Text
If IsNumeric(ID) = False Or ID.Length > 4 Or Pass = Nothing Then
MsgBox("Staff ID is a 4-digit number and Password must not be blank.")
Else
Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
con.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then 'Correct:
MenuForm.Show()
Me.Hide()
CurrentUser = ID
Else 'Incorrect:
MsgBox("Staff ID or Password incorrect.")
txtPassword.Text = ""
txtID.Text = ""
txtID.Focus()
End If
Catch ex As Exception
MsgBox("Database Connection Error.")
End Try
con.Close()
End If
End Sub
End Class
A form to change the password:
The problem here is that lblUser (A clarification for the user to tell them which password will be changed) only outputs the data already within the program as a variable: CurrentUser (as assigned upon successful login). No error is produced but the full name of the user isn't shown (or possibly read from the database).
I'm also unsure how the UPDATE SQL command should be contained within the second procedure, btnAccept_click, here. What the syntax is, basically. I haven't found a clear example to look at.
Imports System.Data.OleDb
Public Class PasswordForm
Private Sub PasswordForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New System.Data.OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Dim Returned(2) As String
CurrentUser = CurrentUser
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Title], [Forename], [Surname] FROM tblStaff WHERE [StaffID]='" & CurrentUser & "'", con)
Try
con.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
'Makes db contents variables
Returned(0) = reader.Item("[Title]").ToString
Returned(1) = reader.Item("[Forename]").ToString
Returned(2) = reader.Item("[Surname]").ToString
End If
reader.Close()
Catch ex As Exception
Me.Hide()
MsgBox("Database Connection Error.")
Finally
con.Close()
End Try
lblUser.Text = "Current User: " & CurrentUser & Returned(0) & Returned(1) & Returned(2)
''Only outputs CurrentUser
End Sub
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccept.Click
Dim Current As String = txtCurrent.text
Dim NewPass As String = txtNew.Text
'Verification
If txtNew.Text = txtConfirm.Text And NewPass.Length <= 20 Then
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE tblStaff SET [Pword]='" & NewPass & "' WHERE [StaffID]='" & CurrentUser & "'", con)
End If
End Sub
End Class
Thank you, again, for anyone with ideas (especially exact code).
Oh and throughout what's here there are no errors thrown. Just missing content.

you are opening the connection in openDB() and you are trying to open it again in form1, this will throw the error you are getting. So comment all the con related lines in your form. Same comment for your passowrd form also.
'Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
'con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
'con.Open()
...
end try

Related

user login in vb.net Windows Form

I'm sorry for disturbing you guys, but I had a question to ask. I'm currently doing a program where user which are in the access database can log in, the code is working but the problem is that when I debug I can only login using 1 user, when I try logging in using another user account it shows Login Invalid and I'm not sure why. I hope someone could pin point what am I doing wrong;
Here's my code;
Imports System.Data.OleDb 'provides classes to connect to the database
Imports System.Data
Imports System.IO
Public Class Login
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Function getcount() As Integer
Using conn As New OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb")
'provider to be used when working with access database
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Select COUNT(*) FROM UserProf_table", conn)
Return cmd.ExecuteScalar()
End Using
End Function
Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDbConnection
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb"
conn.Open()
If getcount() = 1 Then
btnReg.Visible = False
Else
btnReg.Visible = True
End If
MsgBox(conn.State.ToString()) 'to check connection
End Sub
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim idbx As String ' noted that ID is numbers
Dim pwd As String
idbx = idbox.Text
pwd = pwdbox.Text
With cmd
'Open Connection for executereader
If Not conn.State = ConnectionState.Open Then
conn.Open()
End If
'initialized database connection
.Connection = conn
.CommandText = "SELECT UserID, UserPwd FROM UserProf_table WHERE UserID = '" & idbox.Text & "' AND UserPwd = '" & pwdbox.Text & "'"
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If idbx = dr.Item("UserID") And pwd = dr.Item("UserPwd") Then
idbx = SystemInformation.UserName
mainForm.Show()
Me.Hide()
Else
MsgBox("Password or username is incorrect")
idbox.Clear()
pwdbox.Clear()
End If
dr.Close()
End If
End With
'close connection
conn.Close()
End Sub
Private Sub btnReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReg.Click
registerForm.Show() ' Register form
Me.Hide()
End Sub
End Class
Here's my database:
I login using the UserID and UserPwd. And is there a way for me to save the UserID do that I can use it in different form? Thank you in advance
You are always reading the whole username/password list!
You have forgotten a WHERE clause in :
SELECT UserID, UserPwd FROM UserProf_table
WHERE UserId = ???
You can login as the first user because it's the first row returned!
[Also: please don't store passwords as plain text]
You should change your sql command to retrieve only 1 record:
.CommandText = "SELECT UserID,UserPwd FROM UserProf_table WHERE UserId =" + idbx.trim()
Moreover, if you are using Visual Studio, you can use "Watch and QuickWatch Windows" in debug mode to show your variables and make sure they return expected values.
https://msdn.microsoft.com/en-us/library/0taedcee.aspx

How to import the data from excel to the .mdb access file?

Here i m have some problem were export the data which in excel to the format of .mdb. i m trying the code were showing below, but it shows the messageBox
Import Failed, correct Column name in the sheet!
Error Message:
The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine
is there anyone can help me.
Best Regards,
Thanes
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' delete the file with the same and create a new access file
If File.Exists("C:\Users\Admin\Desktop\test\CA\book.mdb") Then
File.Delete("C:\Users\Admin\Desktop\test\CA\book.mdb")
End If
Dim _accessData As Access.Application
_accessData = New Access.Application()
_accessData.Visible = False
_accessData.NewCurrentDatabase("C:\Users\Admin\Desktop\test\CA\book.mdb", Access.AcNewDatabaseFormat.acNewDatabaseFormatAccess2000, , , )
_accessData.CloseCurrentDatabase()
_accessData.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll)
_accessData = Nothing
' initialize the connect string
Dim _filename As String = "C:\Users\Admin\Desktop\test\CA\test.xls"
Dim _conn As String
_conn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Admin\Desktop\test\CA\test.xls" & _filename & ";" & "Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Dim _connection As OleDbConnection = New OleDbConnection(_conn)
'Use OledbCommand object to select all the data from sheet1 and execute an ExecuteNonQuery to import data into Book.mdb.
Dim _command As OleDbCommand = New OleDbCommand()
_command.Connection = _connection
Try
_command.CommandText = "SELECT * INTO [MS Access;Database=C:\Users\Admin\Desktop\test\CA\book.mdb].[Sheet1] FROM [Sheet1$A4:D]"
_connection.Open()
_command.ExecuteNonQuery()
_connection.Close()
MessageBox.Show("The import is complete!")
Catch e1 As Exception
MessageBox.Show("Import Failed, correct Column name in the sheet!" & Environment.NewLine & "Error Message:" & Environment.NewLine & e1.Message)
End Try
End Sub
*Note: the program is can create .mdb file, but cannot import the excel data into it.
i m settle it rdy...thank anyway for the help...
Public Class Form1
Private DBPath As String
Private conn As OleDbConnection
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
''delete the file with the same and create a new access file
If File.Exists("C:\Users\Inari Admin\Desktop\test\CA\test.mdb") Then
File.Delete("C:\Users\Inari Admin\Desktop\test\CA\test.mdb")
End If
DBPath = "C:\Users\Inari Admin\Desktop\test\CA\test.mdb"
' create DB via ADOX if not exists
' NOTE: to use ADOX add reference to COM Microsoft ADO Ext. 2.6 for DDL and Security!
If Not File.Exists(DBPath) Then
Dim cat As New ADOX.Catalog()
cat.Create(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
cat = Nothing
End If
conn = New OleDbConnection(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
conn.Open()
Try
Using cmd As New OleDbCommand("CREATE TABLE [test] ([id] COUNTER PRIMARY KEY, [num] INT, [name] MEMO, [no] INT);", conn)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
If ex IsNot Nothing Then
ex = Nothing
End If
End Try
' initialize the connect string
Dim _filename As String = "C:\Users\Inari Admin\Desktop\test\CA\test.xls"
Dim _conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & _filename & ";" & "Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Dim _connection As OleDbConnection = New OleDbConnection(_conn)
'Use OledbCommand object to select all the data from sheet1 and execute an ExecuteNonQuery to import data into test.mdb.
Dim _command As OleDbCommand = New OleDbCommand()
_command.Connection = _connection
Try
Using conn As New OleDbConnection(_conn)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO [MS Access;Database=" + DBPath + "].[test] SELECT * FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
'_command.CommandText = "SELECT * FROM [Sheet1$]"
'_connection.Open()
'_command.ExecuteNonQuery()
'_connection.Close()
MessageBox.Show("The import is complete!")
Catch e1 As Exception
MessageBox.Show("Import Failed, correct Column name in the sheet!" & Environment.NewLine & "Error Message:" & Environment.NewLine & e1.Message)
End Try
End Sub
End Class

Inserting combo box values?

I'm trying to get my system to insert combo box values into my access database. I always get this very long error whenever I try to click my 'add' button and I somehow get this feeling that it's because of my INSERT statement. This is my whole code for my form. Any help will be greatly appreciated! Thank you
Imports System.Data.OleDb
Public Class AdmMain
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.txtFName.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database1.accdb"
conn.Open()
Dim sqlquery As String = "INSERT INTO students (StudentID, FirstName,MiddleName,LastName,Yr, Section) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
Dim SqlCommand As New System.Data.OleDb.OleDbCommand
SqlCommand.Parameters.AddWithValue("#studid", TxtID.Text)
SqlCommand.Parameters.AddWithValue("#fname", txtFName.Text)
SqlCommand.Parameters.AddWithValue("#mname", txtMName.Text)
SqlCommand.Parameters.AddWithValue("#lname", txtLName.Text)
SqlCommand.Parameters.AddWithValue("#yr", rbdtext)
SqlCommand.Parameters.AddWithValue("#sec", uno)
SqlCommand.Connection = conn
Dim sqlRead As System.Data.OleDb.OleDbDataReader = SqlCommand.ExecuteReader()
MsgBox("One record successfully added!", "Added!")
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Heres the error the keeps showing btw!
http://i.imgur.com/DgjiWqm.png
It looks like you are never assigning a select statement to SqlCommand inside your btnAdd_Click method. Try adding SqlCommand.CommandText = sqlquery.
You need to change your query in this way
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlQuery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#studid", TxtID.Text)
cmd.Parameters.AddWithValue("#fname", txtFName.Text)
cmd.Parameters.AddWithValue("#mname", txtMName.Text)
cmd.Parameters.AddWithValue("#lname", txtLName.Text)
cmd.Parameters.AddWithValue("#yr", rbdtext)
cmd.Parameters.AddWithValue("#sec", uno)
Dim rowsInserted = cmd.ExecuteNonQuery()
if rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
else
MessageBox.Show("Failure to add new record!", "Failure!")
End if
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
I have changed the name of your OleDbCommand object to avoid unnecessary confusion with the class SqlCommand used in SqlClient namespace (Not strictly necessary but nevertheless confusing when reading your code). Then I have used the OleDbCommand constructor that gets both the command text and the connection to be used by your command. This avoids to forget setting these essential properties, finally SECTION is a reserved keyword for MS-Access, thus, when used in query text, you need to encapsulate it between square brackets otherwise you get a SYNTAX ERROR

Visual Basic HowTo: Retrieve Data from .mdf

What am I doing wrong? I have been going at this for a while now... I surrender.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True")
Dim Id As Integer = 2
'With the use of ID, it will get the appName or Application Display Name
sqlCon.Open()
Dim sqlText = "SELECT appName " & _
"FROM appTable " & _
"WHERE Id = #sqlID"
Dim sqlCmd = New SqlCommand(sqlText, sqlCon)
sqlCmd.Parameters.AddWithValue("#sqlID", Id)
'sqlCmd.ToString()
sqlCmd.ExecuteScalar() 'I had these in there before I copied the code over
sqlCon.Close()
Label3.Text = sqlText 'For testing or confirmation it went correctly...
End Using
End Sub
You forgot to call
string apName = sqlCmd.ExecuteScaler();
and retrieve the result.
If a resultset (multiple results) is expected, then call reader = cmd.ExecuteReader() and loop through the results.

Visual Basic 2008 New Search Query

I'm trying to do a search through an access database I added to a project but I get this error: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll"
Additional information: No value given for one or more required parameters.
The idea was to search the database for text entered into a textbox, then display the information on that row within more text boxes.
The code dr = cmd.ExecuteReader is also highlighted as an issue when debugging. I'm using visual basic 2008, and quite new to the whole coding scene so explanations as to why the issue has occurred would be appreciated!
Imports System.Windows.Forms
Imports System.Data.OleDb
Public Class frmSearch
Public con As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim dbProvider As String
Dim dbSource As String
Dim BillingSystemFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillingdatabaseDataSet.BillingInfo' table. You can move, or remove it, as needed.
Me.BillingInfoTableAdapter.Fill(Me.BillingdatabaseDataSet.BillingInfo)
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'Setup the provider
TheDatabase = "/billingdatabase.accdb"
BillingSystemFolder = Application.StartupPath
FullDatabasePath = BillingSystemFolder & TheDatabase
'Set the database and the location of it
dbSource = "Data Source = " & FullDatabasePath
'Set the data source
con.ConnectionString = dbProvider & dbSource
'Set the connection string
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
txtJobNum.Clear()
txtName.Clear()
txtSurname.Clear()
Dim str As String
str = "SELECT * FROM BillingInfo WHERE (Code = " & CodeText.Text & ")"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
dr = cmd.ExecuteReader
While dr.Read()
txtSurname.Text = dr("Surname").ToString
txtName.Text = dr("First Name").ToString
txtJobID.Text = dr("Customer ID").ToString
End While
con.Close()
End Sub
End Class
Probably the field Code is a text field. In this case when you want to search using a particular value for that field you should enclose the value between single quotes.
Something like this
str = "SELECT * FROM BillingInfo WHERE (Code = '" & CodeText.Text & "')"
However this is really a bad practice because this allows to create an Sql Injection attack or it will simply fail because your value contains a single quote.
The correct method is using a parameterized query like this
str = "SELECT * FROM BillingInfo WHERE (Code = #p1)"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = CodeText.Text
dr = cmd.ExecuteReader