Read data from a database in vb.net - sql

So I used this piece of sample code to retrieve data from a MS Access Database and display it on a few textboxes on the form. The following error occurs -
# dr = cmd.ExecuteReader - Data type mismatch in criteria expression.
dr = cmd.ExecuteReader
This is the sample code -
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\example\Desktop\Data.accdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Dim r As Random = New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim str As String
str = "SELECT * FROM Items WHERE (Code = '" & r.Next(1, 3) & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("Description").ToString
TextBox2.Text = dr("Cost").ToString
TextBox3.Text = dr("Price").ToString
End While
myConnection.Close()
End Sub

Try this ..
str = "SELECT * FROM Items WHERE (Code = '" & (r.Next(1, 3)).ToString() & "')"

try this:
str = "SELECT * FROM Items WHERE (Code = '" & cStr(r.Next(1, 3)) & "')"

The table name in the file that you provided for download is "Table1" not "Items".
Change the query string to:
str = "SELECT * FROM Table1 where (Code = '" & r.Next(1, 3) & "')"

Related

Forgot Password Form Issues VB.net

I am trying to create a forgot password screen for my application. I am using the tab control for the different pages. My current code is able to create a user but it is able to create duplicates (Which is an issue needed to be rectified) I then have an issue with the forget password screen not working completely.
My code is:
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Dim usernamevalid As Integer
Dim passwordvalid As Integer
Public Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If User.Text.Length < 4 Then
usernamevalid = 0
ElseIf User.Text.Length > 4 Then
usernamevalid = 1
End If
If Pass.Text.Length < 5 Then
passwordvalid = 0
ElseIf Pass.Text.Length > 5 Then
passwordvalid = 1
End If
If usernamevalid = 0 Then
MsgBox("Username Must Be At Least 5 Characters")
End If
If passwordvalid = 0 Then
MsgBox("Password Must Be At Least 5 Characters")
End If
If passwordvalid And usernamevalid = 1 And Pass.Text = RePass.Text Then
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Daniel\Documents\Robocopy.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = User.Text
DBTestP1 = Pass.Text
sql = "INSERT INTO Robocopy(username,[password],sq,sqa) VALUES('" & DBTest1 & "','" & DBTestP1 & "','" & SQREG.Text & "', '" & SQAREG.Text & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
MsgBox("User Created!")
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
ElseIf Not Pass.Text = RePass.Text Then
MsgBox("Passwords did not match")
End If
End Sub
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim result = MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel)
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If NewPass.Text = ReNewPass.Text Then
Try
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
End Class
The exception it catches is The ConnectionString property has not been initialized
Currently I changed my code to what I think you mean:
Button4's code has been changed as such:
Private Sub ResetPassword_Click(sender As Object, e As EventArgs) Handles ResetPassword.Click
If NewPass.Text = ReNewPass.Text Then
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
End Using
End Using
End If
End Sub
I now get the error for cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
I am getting the error for cmd where it says 'Read Only' Variable cannot be the target of assignment
The only thing I can see wrong with the connection string are extra spaces after 'Data Source='.
Here's an example from connectionstrings.com:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;

The connection string property has not been initialized

I am trying to search my database using the below code, but I am getting the above error.
Private Sub ButtonSearch_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSearch.Click
myConnection.Open()
Textlocation.Clear()
Dim str As String
str = "select * From STUDENTS where ADMINNO like " & "'%" & SearchTextBox.Text & "%'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Textadminac.Text = dr("ADMINNO").ToString
End While
myConnection.Close()
End Sub

VB SQL ACCESS Select Where Like Statement

Net, i'm trying to learn how to display a query result into data grid whenever i click the Search Button as a trigger event for the query.
But nothing happens when i click the Search Button but gives me an error message (Please see link for the screenshot of error message) which i don't understand.
Error: http://s1.postimg.org/di091riv3/error1.jpg
Can you please point me to the right track, Thanks.
Here is my code below
Imports System.Data.OleDb
Public Class SearchForm
Dim con As New OleDbConnection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Statd.SelectedIndexChanged
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
empNum = eNumText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '% " & empLnameText.Text & "' "
' MsgBox("Employee Number " + empNum + empLname + empDept + empStat) 'test statement
With sqlCommand
.CommandText = sqlQuery
.Connection = con
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), Table.Rows(i)("FirstName"), Table.Rows(i)("LastName"), Table.Rows(i)("Department"), Table.Rows(i)("Position"), Table.Rows(i)("Status"), Table.Rows(i)("Years"))
End With
Next
End With
con.Close()
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '%' + ? + '%' "
'It's counter-intuitive, but it's best in .Net to use a new connection object each time
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"), _
cmd As New OleDbCommand(sqlQuery, con)
'Use actual column type and length here
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = empLnameText.Text
con.Open()
DataGridView1.DataSource = cmd.ExecuteReader()
End Using
End Sub
Try to change the % to * in your query, just like this:
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '* " & empLnameText.Text & "' "
Access doesn't use % as wildcard:
http://www.techonthenet.com/access/queries/like.php
I spotted an error in the usage of %. It is used for SQL Server and Not Access SQL use * in place of %

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

declare "data source" in a connection string as 'variable' in VB.NET

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim bs As New BindingSource
m_DataAdapter = New OleDbDataAdapter("SELECT * FROM Table1 ORDER BY ID", "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\rebel23\Desktop\sampledata.mdb")
m_DataAdapter.Fill(m_DataSet)
bs.DataSource = m_DataSet.Tables(0)
BindingNavigator1.BindingSource = bs
txtAnimal.DataBindings.Add("Text", bs, "TextBox6.text")
txtSpecies.DataBindings.Add("Text", bs, "TextBox7.text")
In the above code i want to change the "data source" and declare it as TextBox1.text
So that the user will decide the data source at run time...
Also i want the same for 'Table1' and 'ID'
but how to do that??
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim bs As New BindingSource
Dim myTableName As String
Dim myOrderingColumn As String
Dim mybind1 As String
Dim mybind2 As String
myTableName = TextBox3.Text
myOrderingColumn = TextBox4.Text
mybind1 = TextBox6.Text
mybind2 = TextBox7.Text
m_DataAdapter = New OleDbDataAdapter("SELECT * FROM " & myTableName & " ORDER BY " & myOrderingColumn, "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & TextBox5.Text)
m_DataAdapter.Fill(m_DataSet)
bs.DataSource = m_DataSet.Tables(0)
BindingNavigator1.BindingSource = bs
txtAnimal.DataBindings.Add("Text", bs, "" & TextBox6.Text & "")
txtSpecies.DataBindings.Add("Text", bs, "" & TextBox7.Text & "")
End Sub
hey i got the code man !!!! its working .... thanks a lot for your support and suggestions #matzone
I did it in different way ..
Dim myConn = New OleDb.OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\rebel23\Desktop\sampledata.mdb;Jet OLEDB:Database Password=mypass")
Dim cmd As OleDbCommand
Dim ds as DataSet = New DataSet
myConn.Open() '--> open conn
cmd = New OleDbCommand("SELECT * FROM Table1 ORDER BY ID", myConn)
cmd.Fill(ds, "predator") ' ---> named dataset as Predator
txtAnimal.DataBindings.Add("Text", ds.Tables("predator"), "'" & TextBox6.text & "'")
txtSpecies.DataBindings.Add("Text",ds.Tables("predator"), "'" & TextBox7.text & "'")
' ....
' .....
cmd.Dispose()
ds.Dispose()
cnn.Close()