473,750 Members | 2,680 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

To Add record in Database

81 New Member
Hi,

I have created a form in Visual basic 6.0 for adding/updating the change request made by various users.

Well i am able to update the record through my code in access database.

Can anyone tell me what code should i use to Add record in the database, i also want the new record which will be added in the access database is having some unique no like CRC-CC-date/month/year-incremental number?

I mean as soon anyone will hit the add record form should become compltly blank and with a unique no as per above format.And same has to be updated in the database.

Below is my code, where i have reached

Private Sub Form_Load()
strMyDB = App.Path & "\" & "MyDB.mdb"
txtSearch.Text = DefaultSearchTe xt
End Sub

Private Sub cmdSearch_Click ()
'Search for a client

Dim cn As New ADODB.Connectio n
Dim rs As New ADODB.Recordset
Dim strSQL As String
Dim arWords, iWord As Long
Dim xItem As ListItem
Dim curField As Field
Dim i As Integer
lvClients.ListI tems.Clear
lvClients.Colum nHeaders.Clear

'Open DB connection
'for other DB connection strings go to http://www.thescripts. com/forum/thread572278.ht ml
cn.Open "Provider=Micro soft.Jet.OLEDB. 4.0;" & _
"Data Source=" & strMyDB & ";"

'Put the words searched for into an array and fix any apostrophies
arWords = Split(FixApostr ophies(txtSearc h.Text), " ")

'Start query
strSQL = "SELECT * FROM clients WHERE"

'Build filter requiring all words entered
' to be in username, name_first, or name_last field
For iWord = 0 To UBound(arWords)
If iWord > 0 Then strSQL = strSQL & " AND"
strSQL = strSQL & " ("
strSQL = strSQL & "username like '%" & arWords(iWord) & "%'"
strSQL = strSQL & " OR"
strSQL = strSQL & " name_first like '%" & arWords(iWord) & "%'"
strSQL = strSQL & ")"
Next 'iWord

'Query the database
rs.Open strSQL, cn

'Create column headers for listview based on field names
If Not rs.EOF Then
For Each curField In rs.Fields
lvClients.Colum nHeaders.Add , , curField.name
Next 'curField
End If

'Populate listview with recordset
While Not rs.EOF
'Debug.Print rs("username") & vbTab & rs("phone")
Set xItem = lvClients.ListI tems.Add(, , rs.Fields(0).Va lue)
For i = 1 To (rs.Fields.Coun t - 1)
xItem.ListSubIt ems.Add , , rs.Fields(i).Va lue
Next
'Move to next record in recordset
rs.MoveNext
Wend

'close recordset/connection
rs.Close
cn.Close
'remove references
Set rs = Nothing
Set cn = Nothing
End Sub

Private Sub cmdUpdate_Click ()
'Update client's record
Dim cn As New ADODB.Connectio n
Dim rs As New ADODB.Recordset
Dim strSQL As String

'Open DB connection
cn.Open "Provider=Micro soft.Jet.OLEDB. 4.0;" & _
"Data Source=" & strMyDB & ";"

'create SQL statement to select client from a unique record id
strSQL = "SELECT * FROM clients" & _
" WHERE client_id=" & FixApostrophies (txtClient_Id.T ext)

rs.Open strSQL, cn, adOpenForwardOn ly, adLockOptimisti c

'See if there's a record found
If rs.EOF Then
'record not found
MsgBox "That record no longer exists"
Else
'record found, update record
rs("username") = txtUsername.Tex t
rs("name_last" ) = txtName_Last.Te xt
rs("name_first" ) = txtName_First.T ext
rs("phone") = txtPhone.Text
'update the recordset
rs.Update
End If
'close recordset/connection
rs.Close
cn.Close
'remove references
Set rs = Nothing
Set cn = Nothing
End Sub

Private Sub lvClients_ItemC lick(ByVal Item As MSComctlLib.Lis tItem)
Dim header As ColumnHeader
Dim ret

'Loop through column headers, and populate textboxes with same name (but have 'txt' prefix)
For Each header In lvClients.Colum nHeaders
On Error Resume Next
ret = Me.Controls("tx t" & header.Text)
If Err.Number <> 0 Then
MsgBox Err.Description
Err.Clear
On Error GoTo 0
GoTo NextHeader:
End If

If header.Index > 1 Then
Me.Controls("tx t" & header.Text).Te xt = Item.ListSubIte ms(header.Index - 1).Text
Else
Me.Controls("tx t" & header.Text).Te xt = Item.Text
End If
NextHeader:
Next 'header
End Sub

Function FixApostrophies (ByVal sInput As String) As String
'Use for text that will be included as part of a query
If InStr(1, sInput, "'") Then
'Fix apostrophies
FixApostrophies = Replace(sInput, "'", "''")
Else
FixApostrophies = sInput
End If
End Function

Function RandomInt(ByVal HighVal As Long, Optional ByVal LowVal As Long = 0) As Long
Randomize
RandomInt = CLng((HighVal * Rnd) + LowVal)
End Function

Private Sub Scriptlet1_onsc riptletevent(By Val name As String, ByVal eventData As Variant)

End Sub

Private Sub txtClient_Id_Ch ange()
cmdUpdate.Enabl ed = True
End Sub

'########### Everthing below is unnecessary code ##########
Private Sub txtSearch_GotFo cus()
cmdSearch.Defau lt = True
If txtSearch.Text <> "" And txtSearch.Text = DefaultSearchTe xt Then
txtSearch.Text = Empty
Else
txtSearch.SelSt art = 0
txtSearch.SelLe ngth = Len(txtSearch.T ext)
End If
End Sub


Private Sub txtSearch_LostF ocus()
cmdSearch.Defau lt = False
If txtSearch.Text = "" Then txtSearch.Text = DefaultSearchTe xt
End Sub



Kindly help me. Thanx in advance.
Sep 17 '07 #1
3 2264
hariharanmca
1,977 Top Contributor
You never point what you had tried for insert query.

let cn is your connection

Expand|Select|Wrap|Line Numbers
  1. Dim strSql as string
  2.  
  3. strSql="Insert into <Table Name> (field1,field2,field3) values("  & value1 & ", "  & value1 & ", "  & value1 & ")".
  4. cn.Execute strsql
Sep 17 '07 #2
smugcool
81 New Member
actually i tried few things but didn't work.

I have the tried the above code which is given by you, but it is also not working i am geting error of Sub/function not defined,

Private Sub CmdAdd_Click()
Dim strSql As String
Dim cn As New ADODB.Connectio n
Dim n As String
Where n = 0
strSql = "Insert into <clients> (txtUsername),v alues(CRC-CC-today()-n)"
strSql = "Insert into <clients> (txtUsername),v alues(CRC-CC-today()-n+1)"
cn.Execute strSql
End Sub

Above is the code. Plz go thru it if its correct or changes required.
Sep 17 '07 #3
hariharanmca
1,977 Top Contributor
actually i tried few things but didn't work.

I have the tried the above code which is given by you, but it is also not working i am geting error of Sub/function not defined,

Private Sub CmdAdd_Click()
Dim strSql As String
Dim cn As New ADODB.Connectio n
Dim n As String
Where n = 0
strSql = "Insert into <clients> (txtUsername),values(CRC-CC-today()-n)"
strSql = "Insert into <clients> (txtUsername),values(CRC-CC-today()-n+1)"
cn.Execute strSql
End Sub

Above is the code. Plz go thru it if its correct or changes required.

I think CRC-CC-today() is an VB method and also n.
so the code will be..

Expand|Select|Wrap|Line Numbers
  1. strSql = "Insert into clients (txtUsername) values(" & CRC-CC-today()-n & ")"
  2. cn.Execute strSql
  3.     strSql = "Insert into clients (txtUsername) values('" & CRC-CC-today()-n+1 & "')"
  4.     cn.Execute strSql

For value type the single quote will not be there
it will appear for String and date time type data.
Sep 17 '07 #4

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

Similar topics

5
1728
by: yvan | last post by:
Approximately once a month, a client of ours sends us a bunch of comma-delimited text files which I have to clean up and then import into their MS SQL database. All last week, I was using a Cold Fusion script to upload the cleaned up files and then import the records they contained into the database, though obviously, the process took friggin' forever, and could have been done 500x quicker had I done it directly on the server. My SQL...
6
5681
by: DebbieG | last post by:
I have created a database for a client and was told that it was to be a one-user database. Well, you know the next statement ... now they want 3 people to be able to use the database. (FYI, I have never created a database for multiusers. I've done some searching but not finding what I want.) I have split the database. In Tools, Options, I have set the following: Default open mode = Shared Default record locking = Edited Record
15
4659
by: Steve | last post by:
I have a form with about 25 fields. In the BeforeUpdate event of the form, I have code that sets the default value of each field to its current value. For a new record, I can put the focus in any field to start. If I edit that field and then click on the new record button in the navigation buttons, the form goes to a new record and each field has the default value of the previous record. If I put the focus in any field to start, edit that...
2
15418
by: RC | last post by:
I am getting the following error message. "Write Conflict this record has been changed by another user since you started edting it. If you save the record, you will overwrite the changes...." I have an Access 2002 database running on a single PC, the front and backend have not been separated yet. I have a form where I use a text box to jump from record to record. The form has about 12 bound text boxes on it. The table that is the...
1
5417
by: Scott269 | last post by:
So I've got an old MS Works database I imported into Access. I needed a primary key so I created a record number field that was just the record number I manually inserted when I entered it in the database so I could sort the records by the date at which they were entered. Well now I've deleted some of those records so its of course causing gaps in the records. The record number in Access no longer matches my record number that I...
3
2224
by: domcatanzarite | last post by:
How would one create a button that on click advances the form to the next "non recurring record" as opposed to the next record. The field the button needs to que from has groups of duplicate values. I need it to advance the form to the next group of duplicate values not just the next record.
6
3858
by: polocar | last post by:
Hi, I'm writing a program in Visual C# 2005 Professional Edition. This program connects to a SQL Server 2005 database called "Generations" (in which there is only one table, called "Generations"), and it allows the user to add, edit and delete the various records of the table. "Generations" table has the following fields: "IDPerson", NamePerson", "AgePerson" and "IDParent". A record contains the information about a person (his name, his...
10
12716
by: MLH | last post by:
Suppose, in a multi-user environment, you have append query SQL in a VBA procedure that looks like INSERT INTO MyTable... and the next line reads MyVar=DMax("","MyTable... You can never be certain that MyVar will be set to the key-field value that was created when the Append query ran. Now, there are other ways to do it - I know - that will ensure you 'nab' the correct record. But I was wondering
1
4030
by: Sunray | last post by:
I have a form called the sales form and i have 2 sets of listboxes So what happens is. i add items form the bottom set of list boxes which are bound to a data base to the top set of list boxes which are not bound, I select from the bottom set and add to the top set which works fine, but now i decide to remove an item from the top set. when i tried to use a remove item code it worked fine, it did delete the item form the list but it added...
0
9001
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8838
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9396
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8263
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6808
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2226
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.