Visual Basic HowTo: Retrieve Data from .mdf - sql

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.

Related

How to populate datagridview with dataset from select query?

I'm making a search bar using SELECT query and I want to transfer the results to a DataGridView. But I always get an empty DataGridView.
Nothing is wrong with the query, I already tried to input it manually in access. What am I doing wrong in the code? Here it is:
Using conn = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Dim da As New OleDbDataAdapter(Sql, conn)
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
The issue is as I stated in the comment. ADO.Net uses the % for the like to maintain consistency with most major Sql engines. But I would like to point out that your query is unsafe and subject to SQL injection so I have included an example of your code using a parameter to pass user input to the command.
Also note that the OleDbDataAdapter can be declared in a Using statement the same way you did with the OleDbConnection Note that you may however have to widen the scope of the dataset (ds) if you plan on doing other things with it.
Using conn As OleDbConnection = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE #Product"
Using da As OleDbDataAdapter = New OleDbDataAdapter(Sql, conn)
da.SelectCommand.Parameters.Add("#Product", OleDbType.Varchar).Value = txtSearchProduct.Text & "%"
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
Like Charles has mentioned its always better to use parameters. My answer is a bit different whereas it uses a reader and not an adapter, and a datatable and not an entire dataset. An adapter should only be used if you intend to write back to the table, or typical scenarios include binding procedures. A DataSet is typically used when you have multiple tables and have a need to relate them. Also note, you most likely want a preceding % in your parameter if you want to match the string regardless of the position in the search column.
Try
Using conn = New OleDbConnection("YourConnString")
conn.Open()
Dim Cmd As New OleDbCommand("SELECT * FROM Products WHERE [Product Name] LIKE #Product", conn)
Cmd.Parameters.AddWithValue("#Product", "'%" & txtSearchProduct.Text & "%'")
Dim ProductsRDR As OleDbDataReader = Cmd.ExecuteReader
Dim DTable As New DataTable With {.TableName = "Products"}
DTable.Load(ProductsRDR)
DataGridView1.DataSource = DTable
conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
All you have to do is replacing the * sign with % in your Sql string, just like this:
This is your wrong Sql string:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Change it to this:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "%'"
This should cover most of the common scenarios out there.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

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 read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms?

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

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

WHERE Statement in VB. NET OleDB / SQL Query

Thanks for taking the time to look at my question! I am new to all this and I am trying my best to work out the solution but I keep hitting a brick wall. I'm trying to update a table in a MDB file with the value of a String, where other conditions are met in another part of the table. I realise calling on strings is bad practise!
I think the problem is with the WHERE part of the SQL statement?
Appreciate any help, here is part of the code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Declerations For Calling on
Dim AnimalHouse As String
AnimalHouse = "TestText"
Dim AddressForAssingment As Integer
AddressForAssingment = 1
Dim IDCheckAssignment As Integer
IDCheckAssignment = 1
'Connection Information
Dim myConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ProjectDirectory.Text)
Dim myCommand As New OleDbCommand("INSERT INTO IOInformation SET Description= '" & AnimalHouse & "' WHERE ID_number= '" & AddressForAssingment & "' AND ID_Check= '" & IDCheckAssignment & "'")
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Sub
INSERT and UPDATE are two different commands.
Your query is a mix of both right now, what you want is possibly something like:
UPDATE IOInformation SET Description = .... WHERE ...
Like this. Please look into Parameterized Queries.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Declerations For Calling on
Dim AnimalHouse As String
AnimalHouse = "TestText"
Dim AddressForAssingment As Integer
AddressForAssingment = 1
Dim IDCheckAssignment As Integer
IDCheckAssignment = 1
'Connection Information
Dim myConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ProjectDirectory.Text)
Dim myCommand As New OleDbCommand("Update IOInformation SET [Description] = #animalHouse, WHERE ID_number = #addrForAssn AND ID_Check = #Id))
myCommand.Parameters.AddWithValue("#animalHouse", AnimalHouse)
myCommand.Parameters.AddWithValue("#addrForAssn", AddressForAssingment)
myCommand.Parameters.AddWithValue("#Id", IDCheckAssignment)
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()