473,396 Members | 1,784 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Update Existing Data

8
Hi

could anyone give me some advice where I can get some simple examples of updating data in VB and populating the access database.

Example

If I want to update an existing field on a record - Client table - update Telephone field.

thanks
May 15 '07 #1
1 1784
danp129
323 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. 'This is an example of searching/updating a database from VB6
  2. 'Search example is in cmdSearch_click and the update example is in cmdUpdate_click
  3.  
  4. 'For this example you need to do the following
  5. 'Add reference: Microsoft ActiveX Data Objects x.x Library (use latest version installed)
  6. 'Add component: Microsoft Windows Common Controls 6 sp6
  7. 'Add command buttons: cmdSearch, cmdUpdate
  8.  
  9. 'Add textboxes: ...
  10. 'txtSearch
  11. 'txtClient_id
  12. 'txtUsername
  13. 'txtName_First
  14. 'txtName_Last
  15. 'txtPhone
  16.  
  17. 'Make new access database called MyDB.mdb in path of saved project
  18. 'Make table in database called clients
  19. 'Make fields in table called:...
  20. 'client_id      autonumber
  21. 'username       text
  22. 'name_first     text
  23. 'name_last      text
  24. 'phone          text
  25.  
  26. 'Add some mock client info to the database manually in access
  27.  
  28. Option Explicit
  29. 'Set path to DB
  30. 'Note project must be saved or compiled for app.path to work
  31. 'This assumes db is in same folder as project/exe
  32. Dim strMyDB As String
  33. Const DefaultSearchText = "Search For Client"
  34.  
  35. Private Sub Form_Load()
  36.     strMyDB = App.Path & "\" & "MyDB.mdb"
  37.     txtSearch.Text = DefaultSearchText
  38. End Sub
  39.  
  40. Private Sub cmdSearch_Click()
  41.     'Search for a client
  42.  
  43.     Dim cn As New ADODB.Connection
  44.     Dim rs As New ADODB.Recordset
  45.     Dim strSQL As String
  46.     Dim arWords, iWord As Long
  47.     Dim xItem As ListItem
  48.     Dim curField As Field
  49.     Dim i As Integer
  50.     lvClients.ListItems.Clear
  51.     lvClients.ColumnHeaders.Clear
  52.  
  53.     'Open DB connection
  54.     'for other DB connection strings go to http://www.thescripts.com/forum/thread572278.html
  55.     cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
  56.                "Data Source=" & strMyDB & ";"
  57.  
  58.     'Put the words searched for into an array and fix any apostrophies
  59.     arWords = Split(FixApostrophies(txtSearch.Text), " ")
  60.  
  61.     'Start query
  62.     strSQL = "SELECT * FROM clients WHERE"
  63.  
  64.     'Build filter requiring all words entered
  65.     '   to be in username, name_first, or name_last field
  66.     For iWord = 0 To UBound(arWords)
  67.         If iWord > 0 Then strSQL = strSQL & " AND"
  68.         strSQL = strSQL & " ("
  69.         strSQL = strSQL & "username like '%" & arWords(iWord) & "%'"
  70.         strSQL = strSQL & " OR"
  71.         strSQL = strSQL & " name_first like '%" & arWords(iWord) & "%'"
  72.         strSQL = strSQL & " OR"
  73.         strSQL = strSQL & " name_last like '%" & arWords(iWord) & "%'"
  74.         strSQL = strSQL & ")"
  75.     Next 'iWord
  76.  
  77.     'Query the database
  78.     rs.Open strSQL, cn
  79.  
  80.     'Create column headers for listview based on field names
  81.     If Not rs.EOF Then
  82.         For Each curField In rs.Fields
  83.             lvClients.ColumnHeaders.Add , , curField.Name
  84.         Next 'curField
  85.     End If
  86.  
  87.     'Populate listview with recordset
  88.     While Not rs.EOF
  89.         'Debug.Print rs("username") & vbTab & rs("phone")
  90.         Set xItem = lvClients.ListItems.Add(, , rs.Fields(0).Value)
  91.         For i = 1 To (rs.Fields.Count - 1)
  92.             xItem.ListSubItems.Add , , rs.Fields(i).Value
  93.         Next
  94.         'Move to next record in recordset
  95.         rs.MoveNext
  96.     Wend
  97.  
  98.     'close recordset/connection
  99.     rs.Close
  100.     cn.Close
  101.     'remove references
  102.     Set rs = Nothing
  103.     Set cn = Nothing
  104. End Sub
  105.  
  106. Private Sub cmdUpdate_Click()
  107.     'Update client's record
  108.     Dim cn As New ADODB.Connection
  109.     Dim rs As New ADODB.Recordset
  110.     Dim strSQL As String
  111.  
  112.     'Open DB connection
  113.     cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
  114.                "Data Source=" & strMyDB & ";"
  115.  
  116.     'create SQL statement to select client from a unique record id
  117.     strSQL = "SELECT * FROM clients" & _
  118.         " WHERE client_id=" & FixApostrophies(txtClient_Id.Text)
  119.  
  120.     rs.Open strSQL, cn, adOpenForwardOnly, adLockOptimistic
  121.  
  122.     'See if there's a record found
  123.     If rs.EOF Then
  124.         'record not found
  125.         MsgBox "That record no longer exists"
  126.     Else
  127.         'record found, update record
  128.         rs("username") = txtUsername.Text
  129.         rs("name_last") = txtName_Last.Text
  130.         rs("name_first") = txtName_First.Text
  131.         rs("phone") = txtPhone.Text
  132.         'update the recordset
  133.         rs.Update
  134.     End If
  135.     'close recordset/connection
  136.     rs.Close
  137.     cn.Close
  138.     'remove references
  139.     Set rs = Nothing
  140.     Set cn = Nothing
  141. End Sub
  142.  
  143. Private Sub lvClients_ItemClick(ByVal Item As MSComctlLib.ListItem)
  144.     Dim header As ColumnHeader
  145.     Dim ret
  146.  
  147.     'Loop through column headers, and populate textboxes with same name (but have 'txt' prefix)
  148.     For Each header In lvClients.ColumnHeaders
  149.         On Error Resume Next
  150.         ret = Me.Controls("txt" & header.Text)
  151.         If Err.Number <> 0 Then
  152.             MsgBox Err.Description
  153.             Err.Clear
  154.             On Error GoTo 0
  155.             GoTo NextHeader:
  156.         End If
  157.  
  158.         If header.Index > 1 Then
  159.             Me.Controls("txt" & header.Text).Text = Item.ListSubItems(header.Index - 1).Text
  160.         Else
  161.             Me.Controls("txt" & header.Text).Text = Item.Text
  162.         End If
  163. NextHeader:
  164.     Next 'header
  165. End Sub
  166.  
  167. Function FixApostrophies(ByVal sInput As String) As String
  168.     'Use for text that will be included as part of a query
  169.     If InStr(1, sInput, "'") Then
  170.         'Fix apostrophies
  171.         FixApostrophies = Replace(sInput, "'", "''")
  172.     Else
  173.         FixApostrophies = sInput
  174.     End If
  175. End Function
  176.  
  177. Function RandomInt(ByVal HighVal As Long, Optional ByVal LowVal As Long = 0) As Long
  178.     Randomize
  179.     RandomInt = CLng((HighVal * Rnd) + LowVal)
  180. End Function
  181.  
  182. Private Sub txtClient_Id_Change()
  183.     cmdUpdate.Enabled = True
  184. End Sub
  185.  
  186. '########### Everthing below is unnecessary code ##########
  187. Private Sub txtSearch_GotFocus()
  188.     cmdSearch.Default = True
  189.     If txtSearch.Text <> "" And txtSearch.Text = DefaultSearchText Then
  190.         txtSearch.Text = Empty
  191.     Else
  192.         txtSearch.SelStart = 0
  193.         txtSearch.SelLength = Len(txtSearch.Text)
  194.     End If
  195. End Sub
  196.  
  197.  
  198. Private Sub txtSearch_LostFocus()
  199.     cmdSearch.Default = False
  200.     If txtSearch.Text = "" Then txtSearch.Text = DefaultSearchText
  201. End Sub
Attached Files
File Type: zip VB6_Access.zip (26.1 KB, 102 views)
May 17 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Google Mike | last post by:
I have one table of new records (tableA) that may already exist in tableB. I want to insert these records into tableB with insert if they don't already exist, or update any existing ones with new...
10
by: Jim | last post by:
Hi, Let me explain how I'd generally do things. For a page where the user edits data, I'd generally call it something like editfred.php (for example), the page which updates the data would be...
16
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums...
10
by: Steve Jorgensen | last post by:
Hi all, Over the years, I have had to keep dealing with the same Access restriction - that you can't update a table in a statement that joins it to another non-updateable query or employs a...
0
by: M. David Johnson | last post by:
I cannot get my OleDbDataAdapter to update my database table from my local dataset table. The Knowledge Base doesn't seem to help - see item 10 below. I have a Microsoft Access 2000 database...
1
by: anjangoswami06 | last post by:
Hi, I am interested to know how it is possible to update the data type with "insert" with stl hash_map. Suppose we have, hash_map<const char *, MyDataType, hash_compare<const char*,...
4
by: MN | last post by:
I have to import a tab-delimited text file daily into Access through a macro. All of the data needs to be added to an existing table. Some of the data already exists but may be updated by the...
13
by: dennis | last post by:
Hello, I'm having trouble solving the following problem with DB2 UDB 8.2. I need to create a trigger that performs certain extra constraint validations (temporal uniqueness). One of the tables...
3
by: Fred Chateau | last post by:
Any obvious reason here why data is not being loaded into the database? SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand); SqlCommandBuilder commandBuilder = new...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.