Inserting a Record using VB6 to MS ACCESS

Please read the  article Creating A connection VB6-MSACCESS before reading this tutorial


from the form that we already created create a form having 3 textbox and 1 button



 after creating a form create a database table on your Dabase having a field of PID Datatype of Nummber ProductName Datatype Text Price and Stock with a datatype of number then Save it as tbl_Products




Your Database should Look like this then another is to create a Database Table Named tbl_ID with a field of ID



Take note that fld_ID will have a default Value of 1


after that we are ready for coding, on your vb project form1 double click the button Save

then we will need to do this  code for saving

Dim PID As String
'Declaration of variable of PID this will hold tha value of PID

Dim rstID As New ADODB.Recordset

'Declaration of variable named rstID a recordset take note that if you want to add search and any 'manipulation on the database you need to use a recordset




rstID.Open "Select * from tbl_ID", con, 3, 3
'initialization of rstID to get the value on the database table

PID = rstID.Fields("fld_ID")
' assign the value of fld_ID to PID now the value of PID  = 1


Dim rstadd As New ADODB.Recordset
'a rstadd for inserting a record

rstadd.Open "Select * from tbl_Products", con, 3, 3
'then initialize it by accessing the table on what  we want to papulate

rstadd.AddNew
' rstadd.addnew addnew indicates that we want to add a new record on the database table

        rstadd.Fields("fld_PID") = Val(PID)
        rstadd.Fields("fld_ProductName") = Me.txtProduct.Text
        rstadd.Fields("fld_Price") = Val(Me.txtPrice.Text)
        rstadd.Fields("fld_Stocks") = Val(Me.txtStocks.Text)


' The codes above starting at the end of rstadd.addnew is the assignment of values for the specific field the 'val keyword converts a string to a number, takenote that the name of the textbox should match on the name 'of the textbox that you created.

   

rstadd.Update

'rstadd.Update is a code for updating or making some changes on your database without this code the 'record would not be inserted

rstID.Fields("fld_ID") = Val(rstID.Fields("fld_ID")) + 1
rstID.Update
' for this code we need to update fld_ID so that there is no duplication of the value of PID so the current 'value of fld_ID = 1 added by 1 then it will equal to 2 meaning it will increament by 1

Me.txtProduct.Text = ""
Me.txtPrice.Text = ""
Me.txtStocks.Text = ""

' for this code the textbox will be cleared


Me.txtProduct.SetFocus
' setfocus  for puting the cursor on txtproduct

take note that on the formload you need to call init_con


-happy coding















Walang komento:

Mag-post ng isang Komento