Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly add new records to empty recordset manually?

Tags:

vb6

ado

How to add new records to a new & empty ADODB.Recordset manually?

Right now, here's what I'm doing that isn't working:

Dim rs as ADODB.Recordset
rs.Open
Dim Fields() as String
Fields(0) = "SomeFieldName"

Dim Values() as String
Value(0) = "SomeValue"

rs.AddNew Fields, Values
like image 404
bitcycle Avatar asked Feb 19 '10 03:02

bitcycle


People also ask

What recordset method set to null all the fields and the newly created record is made the current record?

Use the AddNew method to create and add a new record in the Recordset object named by recordset. This method sets the fields to default values, and if no default values are specified, it sets the fields to Null (the default values specified for a table-type Recordset).

What is Recordset in Visual Basic?

A Recordset object represents the records in a base table or the records that result from running a query.

What is Adodb recordset?

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database.


2 Answers

set rs = new ADODB.Recordset
rs.Open "Select SomeFieldName, AnotherFieldName FROM MyTable", myConnection, adOpenDynamic, adLockOptimistic

rs.AddNew
rs("SomeFieldName").Value = "SomeValue"
rs("AnotherFieldName").Value = 1
rs.Update

rs.AddNew
rs("SomeFieldName").Value = "AnotherValue"
rs("AnotherFieldName").Value = 2
rs.Update

rs.Close
like image 160
C-Pound Guru Avatar answered Sep 30 '22 21:09

C-Pound Guru


In-place:

rs.AddNew "SomeFieldName", "SomeValue"

Or in-place multiple fields

rs.AddNew Array("SomeFieldName", "AnotherFieldName"), Array("SomeValue", 1234)

Or using separate vars

Dim Fields As Variant
Dim Values As Variant

Fields = Array("SomeFieldName")
Values = Array("SomeValue")
rs.AddNew Fields, Values

Edit: This is how to synthesize a recordset for the AddNew sample above

Set rs = new Recordset
rs.Fields.Append "SomeFieldName", adVarChar, 1000, adFldIsNullable
rs.Fields.Append "AnotherFieldName", adInteger, , adFldIsNullable
rs.Open

I'm usually using a helper function CreateRecordset as seen this answer.

Update 2018-11-12

You can also use field indexes as ordinals instead of field names as strings for the fields array like this

rs.AddNew Array(0, 1), Array("SomeValue", 1234)
like image 45
wqw Avatar answered Sep 30 '22 23:09

wqw