Microsoft Access databases
Many small businesses keep their data in an Access file. This lesson uses an .accdb file from Ring through ODBC — it makes the file, creates tables, inserts rows with parameters, runs joins and totals, works with dates, and uses a transaction. It runs on Windows with the Microsoft Access Database Engine.
What you will learn#
- what is needed to use Access from Ring (and why it works only on Windows),
- making a new
.accdbfile (ADOX) and connecting withOdbcConnection, - the Access column types and SQL dialect,
- parameters (
?) instead of text joined into a statement, - reading rows with a reader, joins,
GROUP BY,TOP,LIKE, - dates, transactions, closing,
- the limits of Access and when to choose another database.
The tutorial Databases step by step used SQLite and the tutorial Reports with SQL wrote reports with SQL. The ideas are the same; only the driver and a few details of the SQL change.
What you need#
| Need | Why |
|---|---|
| Windows | the Access drivers exist only there |
| the Microsoft Access Database Engine, 64-bit | it brings the ODBC driver Microsoft Access Driver (\.mdb, \.accdb) and the OLEDB provider. It is installed with Microsoft Access or Microsoft 365, or from the free "Access Database Engine Redistributable" |
System.Data.Odbc.dll | the .NET classes for ODBC. They are a NuGet package, not part of the runtime; the RingDotNet package has the file in its bin folder and the program loads it with dnLoad |
The bitness must match. Ring and the .NET runtime here are 64-bit, so the driver must be 64-bit. If a 32-bit Microsoft Office is installed, the 64-bit engine cannot be installed next to it, and the connection fails with "Data source name not found" or "provider not registered". The program checks the registry for the driver and, when anything is missing, prints what is missing and stops without an error (the output below shows the real run of this computer; on Linux the program says that Access needs Windows).
The program#
# Microsoft Access databases - an .accdb file through ODBC: tables, parameters, joins, totals, dates, transactions
# (Windows only: it needs the Microsoft Access Database Engine; anywhere else the program says why it stops)
load "dotnet.ring"
using {
"System.Data.Odbc"
"Microsoft.Win32"
"System"
"System.IO"
}
func main
# 0. What the program needs. Without it, it stops with a message and no error.
cDriver = "Microsoft Access Driver (*.mdb, *.accdb)"
if not iswindows()
? "This tutorial needs Windows: the Microsoft Access drivers exist only there."
return
but not driverInstalled(cDriver)
? "The ODBC driver '" + cDriver + "' is not installed."
? "Install the Microsoft Access Database Engine (64-bit, like Ring and .NET) and run the program again."
return
ok
dnLoad(dnRequest("bridgefolder",[]) + "/System.Data.Odbc.dll") # System.Data.Odbc is a NuGet package, it is not part of the runtime
# 1. A new Access file. The ODBC driver opens files but can not create one, so ADOX (a COM component that comes with Access) does it.
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_access.accdb"])
if new File().Exists(cFile)
new File().Delete(cFile)
ok
if not createDatabase(cFile)
? "A new Access file could not be made (the ADOX component or the ACE OLEDB provider is missing)."
return
ok
? "1. the database file was created: " + new File().Exists(cFile)
# The connection string names the driver and the file (Dbq). The ODBC classes have no generated Ring classes: dnNew makes the
# objects and callMethod / getProp use them.
oConnection = (new OdbcConnection).@New("Driver={" + cDriver + "};Dbq=" + cFile + ";")
oConnection.Open()
? " the connection is: " + oConnection.State
# 2. Tables. Access has its own names for the column types: AUTOINCREMENT (a number that counts by itself), TEXT(n), LONG (a whole
# number), CURRENCY (money with 4 decimals, exact), DATETIME, YESNO.
runSql(oConnection,"CREATE TABLE Customers (Id AUTOINCREMENT PRIMARY KEY, Name TEXT(40), City TEXT(30), Vip YESNO)",[])
runSql(oConnection,"CREATE TABLE Orders (Id AUTOINCREMENT PRIMARY KEY, CustomerId LONG, Total CURRENCY, Ordered DATETIME)",[])
? nl + "2. tables: " + joinList(tableNames(oConnection))
? " columns of Orders: " + joinList(columnNames(oConnection,"Orders"))
# 3. Rows go in with PARAMETERS: a ? in the statement and the values in a list. Never join values into the text of the statement:
# a name with an apostrophe would break it, and a bad text could change what the statement does.
aCustomers = [ ["Ann","Cairo",True], ["Bob O'Neil","Alexandria",False], [arabicName(),"Cairo",True], ["Dina","Giza",False] ]
for aCustomer in aCustomers
runSql(oConnection,"INSERT INTO Customers (Name, City, Vip) VALUES (?, ?, ?)",aCustomer)
next
aOrders = [ [1,120.5,2024,1,15], [1,80,2024,2,3], [2,45.25,2024,2,10], [3,300,2024,3,1], [3,19.99,2024,3,20], [1,60,2024,4,2] ]
for aOrder in aOrders
runSql(oConnection,"INSERT INTO Orders (CustomerId, Total, Ordered) VALUES (?, ?, ?)",[aOrder[1],aOrder[2],new DateTime(aOrder[3],aOrder[4],aOrder[5])])
next
? nl + "3. rows: " + scalar(oConnection,"SELECT COUNT(*) FROM Customers",[]) + " customers, " + scalar(oConnection,"SELECT COUNT(*) FROM Orders",[]) + " orders"
# 4. A query gives rows. Reading goes through a reader: Read() moves to the next row and GetValue(n) reads a column (0 is the first).
? nl + "4. the customers in Cairo, by name:"
aCityRows = rows(oConnection,"SELECT Id, Name, City FROM Customers WHERE City = ? ORDER BY Name",["Cairo"])
for aRow in aCityRows
? " " + aRow[1] + ": " + aRow[2] + " (" + aRow[3] + ")"
next
? " the apostrophe and the Arabic name came back as they went in: " + (scalar(oConnection,"SELECT Name FROM Customers WHERE Id = ?",[2]) = "Bob O'Neil") + ", " + (scalar(oConnection,"SELECT Name FROM Customers WHERE Id = ?",[3]) = arabicName())
# 5. A join puts the data of two tables side by side
? nl + "5. each order with its customer (INNER JOIN):"
aOrderRows = rows(oConnection,"SELECT c.Name, o.Total, o.Ordered FROM Customers AS c INNER JOIN Orders AS o ON c.Id = o.CustomerId ORDER BY o.Ordered",[])
for aRow in aOrderRows
? " " + padRight(shortName(aRow[1]),12) + padLeft(money(aRow[2]),8) + " " + aRow[3]
next
# 6. Totals: GROUP BY makes one row for each customer, with SUM, COUNT and AVG. HAVING filters the groups.
? nl + "6. orders for each customer (customers with 2 orders or more):"
aTotalRows = rows(oConnection,"SELECT c.Name, COUNT(*) AS Orders, SUM(o.Total) AS Total, AVG(o.Total) AS Average FROM Customers AS c INNER JOIN Orders AS o ON c.Id = o.CustomerId GROUP BY c.Name HAVING COUNT(*) >= ? ORDER BY SUM(o.Total) DESC",[2])
for aRow in aTotalRows
? " " + padRight(shortName(aRow[1]),12) + aRow[2] + " orders, total " + money(aRow[3]) + ", average " + money(aRow[4])
next
# 7. TOP n is Access's way to say "the first n rows" (there is no LIMIT). LIKE searches with % for any characters (ODBC style).
? nl + "7. the 2 biggest orders: " + joinList(columnOf(rows(oConnection,"SELECT TOP 2 Total FROM Orders ORDER BY Total DESC",[]),1,"money"))
? " the customers whose name starts with B: " + joinList(columnOf(rows(oConnection,"SELECT Name FROM Customers WHERE Name LIKE ?",["B%"]),1,""))
# 8. Dates. A DateTime object goes in as a parameter and comes back as a DateTime. Access has date functions: Year, Month, Format.
? nl + "8. the total of each month (Month function):"
aMonthRows = rows(oConnection,"SELECT Month(Ordered) AS M, SUM(Total) FROM Orders GROUP BY Month(Ordered) ORDER BY Month(Ordered)",[])
for aRow in aMonthRows
? " month " + aRow[1] + ": " + money(aRow[2])
next
? " orders after 15 February: " + scalar(oConnection,"SELECT COUNT(*) FROM Orders WHERE Ordered > ?",[new DateTime(2024,2,15)])
# 9. Change and delete rows. The statement answers how many rows it changed.
? nl + "9. the orders of Ann under 100 are raised by 10%: " + runSql(oConnection,"UPDATE Orders SET Total = Total * 1.1 WHERE CustomerId = ? AND Total < ?",[1,100]) + " rows"
? " Dina has no orders and is deleted: " + runSql(oConnection,"DELETE FROM Customers WHERE Id = ?",[4]) + " row"
# 10. A transaction makes several statements ONE change: all of them happen or none. Here the second statement fails (a table that
# does not exist), so the first one is undone.
oTransaction = oConnection.BeginTransaction(NULL)
lFailed = False
try
runSqlIn(oConnection,oTransaction,"UPDATE Customers SET City = ? WHERE Id = ?",["Luxor",1])
runSqlIn(oConnection,oTransaction,"UPDATE NoSuchTable SET x = 1",[])
oTransaction.Commit()
catch
lFailed = True
oTransaction.Rollback(NULL)
done
? nl + "10. the second statement failed: " + lFailed + "; the city of Ann is still " + scalar(oConnection,"SELECT City FROM Customers WHERE Id = ?",[1])
# 11. Close the connection. The pool of ODBC keeps connections for reuse, so it is emptied too. The Access engine keeps the FILE open
# until the program ends, so the program does not delete it here.
oConnection.Close()
oConnection.Dispose()
(new OdbcConnection).ReleaseObjectPool()
? nl + "11. the connection is closed; the file stays on the disk until the next run of the program deletes it"
# ---------------------------------------------------------------- the database
# is the ODBC driver registered? (the list of ODBC drivers is in the registry)
func driverInstalled cDriver
try
oMachine = (new Registry).LocalMachine
oKey = oMachine.OpenSubKey("SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers")
if oKey.isNull()
return false
ok
xValue = oKey.GetValue(cDriver) # the text "Installed", or null when the driver is not registered
if isObject(xValue)
return not xValue.isNull()
ok
return true
catch
return false
done
# a new Access file made with ADOX (a COM component of Windows); false when it is not available
func createDatabase cFile
try
oType = new Type().GetTypeFromProgID("ADOX.Catalog")
if oType.isNull()
return false
ok
oCatalog = new Activator().CreateInstance(oType)
oType.callMethod("InvokeMember",["Create","InvokeMethod",dnNull(),oCatalog,["Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + cFile]])
return new File().Exists(cFile)
catch
return false
done
# a command with its parameters (the driver uses them in the order of the ? marks)
func makeCommand oConnection,cSql,aValues
oCommand = oConnection.CreateCommand()
oCommand.CommandText = cSql
oParameters = oCommand.Parameters
nNumber = 0
for xValue in aValues
nNumber++
oParameters.AddWithValue("p" + nNumber,xValue)
next
return oCommand
# a statement that changes data: answers the number of rows
func runSql oConnection,cSql,aValues
return makeCommand(oConnection,cSql,aValues).ExecuteNonQuery()
func runSqlIn oConnection,oTransaction,cSql,aValues
oCommand = makeCommand(oConnection,cSql,aValues)
oCommand.Transaction = oTransaction
return oCommand.ExecuteNonQuery()
# one value: the first column of the first row
func scalar oConnection,cSql,aValues
return makeCommand(oConnection,cSql,aValues).ExecuteScalar()
# all the rows as a list of lists. A date comes back as a text "yyyy-MM-dd", the other values as Ring numbers and texts.
func rows oConnection,cSql,aValues
aRows = []
oReader = makeCommand(oConnection,cSql,aValues).ExecuteReader(NULL)
nColumns = oReader.FieldCount
while oReader.Read()
aRow = []
for nColumn = 0 to nColumns - 1
xValue = oReader.GetValue(nColumn)
if isObject(xValue)
if xValue.typeName() = "System.DateTime"
xValue = xValue.Format("yyyy-MM-dd")
else
xValue = xValue.toString()
ok
ok
aRow + xValue
next
aRows + aRow
end
oReader.Dispose()
return aRows
# the user tables (the schema also lists the system tables of Access)
func tableNames oConnection
aNames = []
aTableRows = oConnection.GetSchema("Tables").Rows.toList()
for oRow in aTableRows
if oRow.Item("TABLE_TYPE") = "TABLE"
aNames + oRow.Item("TABLE_NAME")
ok
next
return sort(aNames)
# the column names and types of a table: an empty query (WHERE 1 = 0) describes the columns without reading rows
func columnNames oConnection,cTable
aNames = []
oReader = makeCommand(oConnection,"SELECT * FROM " + cTable + " WHERE 1 = 0",[]).ExecuteReader(NULL)
for nColumn = 0 to oReader.FieldCount - 1
aNames + (oReader.GetName(nColumn) + " (" + lower(oReader.GetDataTypeName(nColumn)) + ")")
next
oReader.Dispose()
return aNames
# ---------------------------------------------------------------- small helpers
# an Arabic name as UTF-8 bytes (a Ring text is a text of bytes)
func arabicName
return char(216) + char(163) + char(216) + char(173) + char(217) + char(133) + char(216) + char(175)
# the first word, so that the Arabic name does not disturb the columns
func shortName cName
cShort = cName
if cName = arabicName()
cShort = "(Arabic)"
ok
return cShort
func money nValue
nRounded = floor(nValue * 100 + 0.5)
nUnits = floor(nRounded / 100)
nCents = nRounded - nUnits * 100
cCents = "" + nCents
if nCents < 10
cCents = "0" + cCents
ok
return "" + nUnits + "." + cCents
func columnOf aRows,nColumn,cFormat
aValues = []
for aRow in aRows
if cFormat = "money"
aValues + money(aRow[nColumn])
else
aValues + shortName(aRow[nColumn])
ok
next
return aValues
func joinList aList
cText = ""
for item in aList
if cText != ""
cText += ", "
ok
cText += "" + item
next
return cText
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))
func padLeft cText,nWidth
return copy(" ",nWidth - len(cText)) + cText1. the database file was created: 1
the connection is: Open
2. tables: Customers, Orders
columns of Orders: Id (counter), CustomerId (integer), Total (currency), Ordered (datetime)
3. rows: 4 customers, 6 orders
4. the customers in Cairo, by name:
1: Ann (Cairo)
3: أحمد (Cairo)
the apostrophe and the Arabic name came back as they went in: 1, 1
5. each order with its customer (INNER JOIN):
Ann 120.50 2024-01-15
Ann 80.00 2024-02-03
Bob O'Neil 45.25 2024-02-10
(Arabic) 300.00 2024-03-01
(Arabic) 19.99 2024-03-20
Ann 60.00 2024-04-02
6. orders for each customer (customers with 2 orders or more):
(Arabic) 2 orders, total 319.99, average 160.00
Ann 3 orders, total 260.50, average 86.83
7. the 2 biggest orders: 300.00, 120.50
the customers whose name starts with B: Bob O'Neil
8. the total of each month (Month function):
month 1: 120.50
month 2: 125.25
month 3: 319.99
month 4: 60.00
orders after 15 February: 3
9. the orders of Ann under 100 are raised by 10%: 2 rows
Dina has no orders and is deleted: 1 row
10. the second statement failed: 1; the city of Ann is still Cairo
11. the connection is closed; the file stays on the disk until the next run of the program deletes itThis program uses a few generic functions (dnNew, dnStatic, dnType, callMethod, getProp, setProp, dnNull) where a class cannot be used. The lesson The generic functions explains them.
How it works#
A new file#
The ODBC driver opens Access files but cannot create one. ADOX can: it is a COM component that comes with Access, and Catalog.Create(connection string) makes an empty .accdb. The program reaches it through reflection: Type.GetTypeFromProgID("ADOX.Catalog"), Activator.CreateInstance, and Type.InvokeMember("Create", ...) with the connection string of the OLEDB provider (Provider=Microsoft.ACE.OLEDB.16.0;Data Source=file). If you already have an Access file, skip this step and just open it.
The connection#
Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\path\file.accdb; names the driver and the file. For a file with a database password add Pwd=secret;; for a read-only open add ReadOnly=1;. The classes of System.Data.Odbc have no generated Ring classes, so the program makes them with dnNew(type, [arguments]) and uses callMethod and getProp (Core concepts, Plain objects). A command is made with CreateCommand(), its CommandText is the SQL, and ExecuteNonQuery() runs a statement that changes data (the answer is the number of rows), ExecuteScalar() gives one value and ExecuteReader() gives rows.
Column types and SQL#
Access has its own names for types and a few differences in its SQL:
| Wanted | Access SQL |
|---|---|
| a number that counts by itself | AUTOINCREMENT (or COUNTER) |
| text of up to n characters | TEXT(n) (up to 255) or MEMO for long text |
| a whole number | LONG (4 bytes) or INTEGER (2 bytes) |
| money, exact | CURRENCY (fixed 4 decimals) |
| date and time | DATETIME |
| yes or no | YESNO |
| the first n rows | SELECT TOP n ... (there is no LIMIT) |
| a name with a space or a reserved word | in brackets: [Order Date] |
Searching with LIKE uses % and _ through ODBC (in the Access program itself it is * and ?). SELECT * FROM T WHERE 1 = 0 returns no rows but describes the columns, which the program uses to list the column names and types (GetSchema("Columns", restrictions) answers "Optional feature not implemented" with this driver; GetSchema("Tables") works).
Parameters#
INSERT INTO Customers (Name, City, Vip) VALUES (?, ?, ?) has placeholders; the values go into the command's Parameters (AddWithValue). The driver uses them in the order of the ? marks, so the names do not matter. Parameters are not only a convenience: a name such as Bob O'Neil would break a statement made by joining text (the apostrophe ends the text), and a value such as x'; DROP TABLE Customers; -- could change what the statement does. As a parameter it is plain data. Never put a value into the text of a statement. The program shows that the apostrophe and the Arabic name come back exactly as they went in: Access stores Unicode text.
Reading rows#
ExecuteReader() gives a reader; Read() moves to the next row and answers false at the end; GetValue(n) reads column n (0 is the first). FieldCount, GetName and GetDataTypeName describe the columns. Numbers and CURRENCY come back as Ring numbers, text as text and a DATETIME as a .NET DateTime, which the program formats with Format("yyyy-MM-dd"). A column without a value is a NULL (System.DBNull): test for it before you use the value, and remember that COUNT(column) does not count NULL values while COUNT(*) counts rows. Dispose the reader (Dispose()) before you run the next command on the same connection.
Joins and totals#
INNER JOIN ... ON c.Id = o.CustomerId puts the orders next to their customers. GROUP BY makes one row for each group with COUNT, SUM and AVG; HAVING filters the groups (where WHERE filters the rows before they are grouped). The result shows that customers with fewer than two orders are not listed. SUM of a currency column is exact, which is why money is CURRENCY and not a floating-point number (the tutorial Money).
Dates#
A DateTime object goes in as a parameter and the comparison Ordered > ? works with real dates, so there is no need for the Access date literal #2/15/2024# (which also depends on the format of the computer). Access has date functions in SQL: Year(d), Month(d), Day(d), DateAdd, DateDiff and Format(d, "yyyy-mm").
Transactions#
BeginTransaction() makes several statements one change: Commit() keeps them, Rollback() undoes them. In step 10 the first UPDATE is correct and the second one names a table that does not exist, so the program rolls everything back, and the city of Ann is still Cairo. Every command that belongs to the transaction needs Transaction set to it (runSqlIn). Use a transaction whenever two changes must stay together (a transfer between two accounts, an order with its lines); it is also much faster for many inserts, because Access writes to the disk once at the end.
Closing#
Close the connection (Close(), Dispose()) and call OdbcConnection.ReleaseObjectPool(): ODBC keeps closed connections for reuse. The Access engine keeps the file open until the program ends, so the program cannot delete its test file at once (a .laccdb lock file appears next to the database while it is open). The program removes the old file at the start of the next run.
Limits and advice#
- Size and users. An Access file is limited to 2 GB and is meant for a few users on a fast local disk; there is no server, every program opens the file itself. It is not a good choice for a web site with many visitors or for a file on a slow network share.
- Backups. The file is the database: copy it when no program has it open (or after compact and repair, which the
JRO.JetEngineCOM object does). - Old files.
.mdbfiles of Access 97 or 2000 may need the older Jet engine, which has no 64-bit version; open them in Access and save them as.accdb. - Moving on. When the data grows or many users need it, move it to SQLite (the tutorial Databases step by step, a file without a server) or to SQL Server and use Entity Framework (the tutorial Entity objects and migrations). The Access driver can read the old file for the copy. The same ODBC driver family also reads Excel and text/CSV files (
Microsoft Excel Driver,Microsoft Access Text Driver) with the same code.
samples/UsingDotNet/tests/test_access.ring tests all of this with 29 checks (Unicode, NULL, transactions, an attack text) and skips itself where Access is not available.
What you learned#
- Access needs Windows, the 64-bit Access Database Engine and
System.Data.Odbc.dll, - ADOX makes a new file; ODBC opens it,
- the Access column types and the small differences of its SQL,
- parameters instead of text in statements,
- readers, joins, grouping, dates and transactions,
- the limits of Access.
Exercises#
- Add a table
Productsand a tableOrderLinesand make a report of the quantity sold for each product. - Write
insertMany(oConnection, cSql, aRows)that inserts a list of rows inside one transaction, and compare its time with single inserts for 1000 rows (the tutorial Speed — measure first). - Write
export(oConnection, cTable, cFile)that writes a table as JSON (the tutorial Writing JSON as a stream). - Open an existing
.accdbfile of your own and list its tables and columns.