How to create table with Autonumber field in MS - Access at run time?
Asked Answered
F

7

6

I am working with MS-Access and JSP. I want to know that how can we create table with autonumber field and with primary key.

query="Create Table Registration_A (Reg_No PRIMARY KEY AUTOINCREMENT, FName varchar(2))";

But its giving syntax error. What's the correct syntax?

Fuzzy answered 17/8, 2011 at 12:2 Comment(0)
E
6
CREATE TABLE Registration_A (
Reg_No AUTOINCREMENT, 
FName VARCHAR(2), 
CONSTRAINT RegA_PK PRIMARY KEY(Reg_No))
Equality answered 17/8, 2011 at 12:6 Comment(5)
stat=conn.createStatement(); stat.executeUpdate("CREATE TABLE Registration_A (Reg_No AUTOINCREMENT, FName VARCHAR(2),CONSTRAINT RegA_PK PRIMARY KEY(Reg_No))"); I used like this but still the same error.Fuzzy
Works for me directly in access.Equality
stats2=conn.createStatement(); stats2.executeUpdate("CREATE TABLE Registration_A (Reg_No AUTOINCREMENT, FName VARCHAR(2),CONSTRAINT RegA_PK PRIMARY KEY(Reg_No))"); I used like this but still this is giving same syntax error.Fuzzy
I am using JSP and I want to create table at runtime in msaccess database; In this table I want autoincrement and primary key.Fuzzy
stats2.executeUpdate("CREATE TABLE Registration_A(Reg_No Autoincrement, FName VARCHAR(2),Primary Key(Reg_No))"); This works using JSP; Thanks a lotFuzzy
L
3

You can use the COUNTER keyword to create an AutoNumber field using DDL. I just tested this in a Java console app and it worked for me under both the JDBC-ODBC Bridge and UCanAccess:

String query = 
        "CREATE TABLE Registration_A (" +
            "Reg_No COUNTER PRIMARY KEY, " +
            "FName VARCHAR(2))";
Statement stmt = con.createStatement();
stmt.executeUpdate(query);
Lawyer answered 11/7, 2014 at 9:35 Comment(0)
M
2

Seven years later, I don't see how to do this in DAO in any of the answers above or anywhere else on any Stack Exchange site. So here is the method I've worked out. The following VBA code creates a table with an autonumber field as primary key, puts some arbitrary data in it, then opens the table to show the results. I've run this code successfully in Access 2007.

Sub Make_Table_With_Autonum_Using_DAO()

Dim oDB As DAO.Database: Set oDB = CurrentDb()
Dim oTable  As DAO.TableDef, sObjTable As String: sObjTable = "table_name"
Dim oField As DAO.Field, oIndex As DAO.Index
Dim oRS As DAO.Recordset

Set oTable = oDB.CreateTableDef(sObjTable)
With oTable
    Set oField = .CreateField("ID_Object", dbLong)      ' Create ID field.
        oField.Attributes = dbAutoIncrField                 ' Make it autoincrement.
        .Fields.Append oField                               ' Add to table's Fields collection.
        Set oIndex = .CreateIndex("Index_Object")           ' Create index.
        oIndex.Primary = True                               ' Make it a primary key.
        Set oField = oIndex.CreateField("ID_Object")        ' Make index field for ID field.
        oIndex.Fields.Append oField                         ' Add it to index's Fields coll'n.
        .Indexes.Append oIndex                              ' Add index to table's Indexes coll'n.
        Set oIndex = Nothing                                ' Remove index from memory.
        Set oField = Nothing                                ' Remove field from memory.
    .Fields.Append .CreateField("field2", dbText)         ' Create and add other fields to
    .Fields.Append .CreateField("field3", dbInteger)      '       table's Fields collection.
    ' etc.
  End With
oDB.TableDefs.Append oTable                       ' Add table to database's TableDefs collection.
Set oTable = Nothing

Set oRS = oDB.OpenRecordset(sObjTable)            ' Enter arbitrary data into table.
oRS.AddNew: oRS!Field2 = "text 1": oRS!field3 = 123: oRS.Update
oRS.AddNew: oRS!Field2 = "text 2": oRS!field3 = 456: oRS.Update
oRS.AddNew: oRS!Field2 = "text 3": oRS!field3 = 789: oRS.Update
oRS.Close

DoCmd.OpenTable (sObjTable)
oDB.Close
Set oRS = Nothing
Set oDB = Nothing

End Sub

The Microsoft documentation for the necessary VBA elements, in order of appearance in the code, is:

That documentation says everything that needs to be known, but doesn't put it all together to explain how to make the autonumber primary key. The following MS documentation (no longer available directly from MS) does explain how to make the autonumber field, but not how to make it the primary key.

In the following post on a Microsoft community forum, the accepted answer by Andrey Artemyev explains the whole thing.

My code above is essentially the same as his in that answer, with some additional commentary to explain what's going on.

Misdeal answered 28/12, 2018 at 20:52 Comment(0)
S
1

This example uses ADOX to create a access table with an autonumber primary key

ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
ADOX.Key tableKey = new Key();
ADOX.Column col = new Column();
String connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\test.accdb; Jet OLEDB:Database Password=";

 cat.Create(ConnString);

 // Define column with AutoIncrement features
 col.Name = "ID";
 col.Type = ADOX.DataTypeEnum.adInteger;
 col.ParentCatalog = cat;
 col.Properties["AutoIncrement"].Value = true;

 table.Name = "Security";
 table.Columns.Append(col);    // default data type is text[255]
 table.Columns.Append("Username", ADOX.DataTypeEnum.adVarWChar, 255);
 table.Columns.Append("Password", ADOX.DataTypeEnum.adVarWChar, 255);
 table.Columns.Append("Engineer", ADOX.DataTypeEnum.adBoolean);
 table.Columns.Append("Default", ADOX.DataTypeEnum.adBoolean);

 // Set ID as primary key
 tableKey.Name = "Primary Key";
 tableKey.Columns.Append("ID");
 tableKey.Type = KeyTypeEnum.adKeyPrimary;

 // Add table to database
 cat.Tables.Append(table);
Scrip answered 5/2, 2013 at 21:14 Comment(0)
C
1

You need to mention the data type first, then the Primary Key.

query="Create Table Registration_A (Reg_No AUTOINCREMENT PRIMARY KEY, FName varchar(2))";
Cruciate answered 16/12, 2014 at 14:10 Comment(0)
J
0

Try this On

 Create Table Registration_A 
       (
         Reg_No AUTOINCREMENT,
         FName varchar(2),
         PRIMARY KEY(Reg_No)
       );     
Johnajohnath answered 1/10, 2012 at 11:14 Comment(0)
T
-1
CREATE TABLE `Tablename` (Field1 AUTOINCREMENT CONSTRAINT `Primarykey` PRIMARY
KEY, `Field2` DATETIME, `Field3` TEXT(25), `Field4` DOUBLE);
Transpire answered 12/4, 2018 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.