updating fields in microsoft access 2000 thru visual basic - ms-access

i created a program that add and returns equipment, my problem is, its because my borrowing table and my return equipments table are in one table only..representing these fields
"productnumber"
"productname"
"dateborrowed"
"datereturned"
"borrowername"
"status"
what i want to do here is when a user returns an equipment, entering the same data on the fields would make errors on my database..especially on my productnumber because that is my primary key, so i decided to have a data grid in my return equipment form, so if a user return an equipment, all i will do is to update the datereturned field in my database..guys? can you help me with the codes?

As you have not indicated what it you specifically you need help with, I'll start by giving you the simple query to perform the update then I am going on to show you how to interact with Access.
The query to update datereturned:
str = "UPDATE 'Your Table Name' SET datereturned = " & now ' This is your update query.
First thing to do is create a connection the the Access Database:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=D:\Tecnical Stu"& _
"dy\Complete_Code\Ch08\data\NorthWind.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString )
Found at:
http://p2p.wrox.com/ado-net/28703-how-vbulletin-net-connect-access-database.html
Next you should perform the update:
dbConnection .Open()
str = "UPDATE 'Your Table Name' SET datereturned = " & now ' This is your update query.
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery
Here is a class that will allow you to perform the interactions, easily and simply.
Imports System.Data.OleDb
Public Class Form1 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e as _
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_
Data Source=C:\emp.mdb;")
'provider to be used when working with access database
cn.Open()
cmd = New OleDbCommand("select * from table1", cn)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr(0)
TextBox2.Text = dr(1)
TextBox3.Text = dr(2)
' loading data into TextBoxes by column index
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Class
When you run the code and click the Button, records from Table1 of the Emp database will be displayed in the TextBoxes.
Retrieving records with a Console Application
Imports System.Data.OleDb
Imports System.Console
Module Module1
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Sub Main()
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;_
Persist Security Info=False")
cn.Open()
cmd = New OleDbCommand("select * from table1", cn)
dr = cmd.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
'writing to console
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Module
Code for Inserting a Record
Imports System.Data.OleDb
Public Class Form2 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button2.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;")
cn.Open()
str = "insert into table1 values(" & CInt(TextBox1.Text) & ",'" & TextBox2.Text & "','" &_
TextBox3.Text & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted
Catch
End Try
cn.Close()
End Sub
End Class
Found at:
http://www.startvbdotnet.com/ado/msaccess.aspx

You need to split the product and borrow/return data into two tables:
product:
"productnumber"
"productname"
borrowed:
borrowedID (use a simple autonumber)
productnumber (foreign key linked to productnumber in the product table)
"dateborrowed"
"datereturned"
"status"
borrowerID (foreign key linked to borrower table)
a third table for borrowers/customers would also be in order
borrowers:
borrowerID
"borrowername"

Related

MYSQL connection string in old VB.NET project in Access

I have a very old project that uses an Access DB (.mdb) and uses various connections from various pages. Some include OLE DB, DAO, ADO. I have over 200 pages with various connections. I'm moving over to MySQL and want to cleanup this mess. Starting with OLEDB I'm having trouble with a connection that will allow me to keep the rest of my code (or even if it can be done?)
Yes I have looked at the various examples in: http://www.connectionstrings.com/net-framework-data-provider-for-ole-db/
Here is one of the many pages I need to move to MySQL connection:
Partial Class mysql_a_Checkoff
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click, Button1.DataBinding
'*** Code to insert class checkoff into class_record table ***
For index As Integer = 0 To GridView1.Rows.Count - 1
'Programmatically access the Checkbox from the TemplateField
Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
'If it is checked, insert it into class records table
If cb.Checked Then
'Code to insert into DB table
Dim FDID As String = GridView1.Rows(index).Cells(1).Text.ToString
Dim Instructor As String = User.Identity.Name()
Dim DateCompleted As Date = TextBox1.Text
Dim Completed As Boolean = True
Dim Enrolled As Boolean = False
Dim UserName As String = GridView1.Rows(index).Cells(4).Text.ToString
Dim ClassName As String = DropDownList1.SelectedValue.ToString
Dim ClassDate As Date = CDate(TextBox1.Text)
Dim WaitListed As Boolean = False
Dim Walkin As Boolean = False
response.write("Yes - ")
InsertClassRecord(UserName, Instructor, DateCompleted, Completed, Enrolled, ClassName, ClassDate, WaitListed, Walkin)
End If
Next
Response.Redirect("i_toc.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
TextBox1.Text = Now.Date
End If
End Sub
Public Function InsertClassRecord(ByVal UserName As String, ByVal Instructor As String, _
ByVal DateCompleted As Date, ByVal Completed As Boolean, _
ByVal Enrolled As Boolean, ByVal ClassName As String, _
ByVal ClassDate As Date, ByVal WaitListed As Boolean, _
ByVal Walkin As Boolean) As Object
Dim connStr As String = "Provider=SQLOLEDB;Server=localhost;Database=mysql_training;Uid=myUsr;Pwd=myPwd;"
conn.ConnectionString = connStr
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[WaitListed]," & _
"[Instructor],[DateCompleted],[Completed],[Walkin]) VALUES " & _
"(#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #WaitListed, " & _
"#Instructor, #DateCompleted, #Completed, #Walkin) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.ToString())
comm.Parameters.AddWithValue("#ClassTime", "0800")
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", Enrolled)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#WaitListed", WaitListed)
comm.Parameters.AddWithValue("#Instructor", Instructor)
comm.Parameters.AddWithValue("#DateCompleted", DateCompleted)
comm.Parameters.AddWithValue("#Completed", Completed)
comm.Parameters.AddWithValue("#Walkin", Walkin)
Dim result As Integer = comm.ExecuteNonQuery()
conn.Close()
Return True
End Function
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
e.Row.Cells(4).Visible = False
End Sub
End Class
Not sure I fully understand the question, but I'll take a stab at it.
Download the MySQL NET Connector and add a reference to your project. Any place where you are using a OleDBConnection or OleDBCommand you will need to change that to MySqlConnection and MySqlCommand respectively. This should allow you to reuse you existing logic as much as possible.
For example, in your InsertClassRecord method you would change this
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
to this
Dim comm As New MySqlCommand(sql, conn)
And you should be able to keep the existing logic

update query not working when i attach the content of text box using data reader on page load

Code works fine when i remove the page load content. this is a form which will allow user to edit the data already present in database. i just want to let a user edit a form which he have already submitted.
This is the code:
Dim con As New SqlConnection("Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True")
Dim cmd, com As New SqlCommand
Dim dr As SqlDataReader
Dim n, d, a As Integer
Dim returnValue As Object
Dim str As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str = "select * from School where RollNo=11"
com = New SqlCommand(str, con)
dr = com.ExecuteReader()
con.Open()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
con.Close()
dr.Close()
End Sub
Protected Sub Next_Click(sender As Object, e As EventArgs) Handles [Next].Click
Try
cmd.CommandText = "Update School SET RollNo='" & Enroll.Text & "', Name='" & Name.Text & "', Class='" & Class.Text & "' where RollNo=11 "
cmd.Connection = con
con.Open()
MsgBox("Connection is Open ! ")
n = cmd.ExecuteNonQuery
If n > 0 Then
MsgBox("data inserted successfully")
Else
MsgBox("data insertion failed")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Sub
You have tagged your question with MySql but in code you use the classes for Sql Server and a connection string specific to Sql Server.
So you should clarify this point. However, in the meantime I wish to give an answer to some errors in your Page_Load event handler:
First you need to check if the call to Page_Load is a postback from other controls and avoid to reload the data from the database in that case. See ASP.NET Page Life Cycle
Second, open the connection before executing the reader
Dim constring = "Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str = "select * from School where RollNo=11"
If Not IsPostBack Then
Using con = new SqlConnection(conString)
Using cmd = new SqlCommand(str, con)
con.Open()
Using dr = com.ExecuteReader()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
End Using
End Using
End Using
End If
End Sub
As you can see there are other improvements: No more global variables for connection, command and reader and Using Statement around the disposable objects.
If this code is really intended to run against a MySql database then you need to use the appropriate classes like MySqlConnection, MySqlCommand, MySqlDataReader etc.. and fix the connectionstring

VB.NET: can't read database records with MySQL Data Reader dr.HasRows

when i click the button 2 with the valid ID No. on the text box it always shows the message box "Invalid ID No." but if i remove the IF statement, it shows database records and it works fine, but i need this IF statement, i think the problem here is the dr.HasRows but i don't know what to put.
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
da.SelectCommand = cmd
da.Fill(DataSet1, "db")
If dr.HasRows Then
Label2.DataBindings.Add("text", DataSet1, "db.fname")
Label10.DataBindings.Add("text", DataSet1, "db.mi")
Label11.DataBindings.Add("text", DataSet1, "db.lname")
Label12.DataBindings.Add("text", DataSet1, "db.yr")
Label13.DataBindings.Add("text", DataSet1, "db.sec")
Label14.DataBindings.Add("text", DataSet1, "db.vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Label2.DataBindings.Clear()
Label10.DataBindings.Clear()
Label11.DataBindings.Clear()
Label12.DataBindings.Clear()
Label13.DataBindings.Clear()
Label14.DataBindings.Clear()
End Sub
End Class
You need to use Parameterized query to prevent SQL Injection
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
command.Parameters.AddWithValue("#idn", TextBox1.Text)
You don't need to use DataSet and DataAdapter if you are using a DataReader because you could convert your DataReader to a DataTable:
dr = command.ExecuteReader() ' Get Data Reader Rows
dt.Load(dr) 'Convert DataReader into DataTable
Which now could be bind to your Label or TextBox:
Label2.DataBindings.Add("Text", dt, "fname")
You don't need then to use HasRows property to check if DataReader has rows, instead you could check the Row Count of your DataTable:
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
End If
I am also using the Using statement in dotNet specially for connection so that you don't have to close:
Using connection As New MySqlConnection(connectionString)
'More code here
End Using ' Close the connection automatically
Check Complete Code Below:
Imports MySql.Data.MySqlClient
Public Class Form16
Dim connectionString as String = "server = localhost; user id = root;password=root; database = db"
Dim dt as DataTable
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Using connection As New MySqlConnection(connectionString)
' Use Parameterized query
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
Dim dr As MySqlDataReader
' Add idn value using parameterized query
command.Parameters.AddWithValue("#idn", TextBox1.Text)
Try
connection.Open() ' Open Connection
dr = command.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
Label10.DataBindings.Add("Text", dt, "mi")
Label11.DataBindings.Add("Text", dt, "lname")
Label12.DataBindings.Add("Text", dt, "yr")
Label13.DataBindings.Add("Text", dt, "sec")
Label14.DataBindings.Add("Text", dt, "vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Sub
End Class
You have done more work than you have to...if you are going to use a datareader, your code should end up looking something like this. (I have not tested this code)
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
if dr.read then
Label2.text = dr("fname")
Label10.text = dr("mi")
Label11.text = dr("lname")
Label12.text = dr("yr")
Label13.text = dr("sec")
Label14.text = dr("vstatus")
else
MessageBox.show("Invalid ID Number")
endif
End Class

Update SQL statement in vb.net

I am new in VB.NET and as well as SQL. I want to update records in my database. I made a dummy in my database.
Example the values are: ID = 1, name=Cath, age=21
In my interface made in VB.NET, I update the values example : name = txtName.Text and age = txtAge.Text where ID = 1. This is in my main form. In my main form, I have "view" button informing that by clicking that button, new form would pop up and would view the updated values by the user. The program does not have any errors except that when I want to update again the values in my SQL, It record BUT when I click "view" button again, It will show the previous inputted by the user (the first update upon running the interface). What should be the solution?
This is my code:
Mainform:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MessageBox.Show("Successful connection")
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully Added!")
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim date_now As String
date_now = Format(dtpDate.Value, "yyyy-MM-dd")
Dim SQLStatement As String = "UPDATE people SET name='" & txtName.Text & "', date ='" & date_now & "' WHERE 1"
SaveNames(SQLStatement)
End Sub
Form 2: (where the updated data would be viewed)
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
'====retrieve / update values in database=============
Dim SQLStatement As String = "SELECT name, date FROM people"
ViewInfos(SQLStatement)
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub ViewInfos(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
'--read the records in database in phpmyadmin gui---
Dim myReader As MySqlDataReader = cmd.ExecuteReader
If myReader.Read Then
lblName.Text = myReader.GetString(0)
lblDate.Text = myReader.GetString(1)
End If
myReader.Close()
MsgBox("Records Successfully Retrieved")
End Sub
Any help would be appreciated. Thanks!
You are leaving your connection string open when you update sql, thus when you try to retrieve the data, your condition closes the connection without reading the data or updating your textboxes.
Take out the .ExecuteNonQuery() from the ViewInfos() method.
Refer to your forms via variables not via the form name:
Dim myForm as New Form2()
myForm.Show()

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()