pyodbc - add column to MS Access with default value

烂漫一生 提交于 2019-12-02 05:09:33

Sadly, the Access ODBC driver simply does not support the DEFAULT clause for a column in CREATE/ALTER TABLE statements. The ODBC driver and OLEDB provider for Access have diverged somewhat in their DDL support, so unfortunately we can get inconsistent results for the same DDL statement as illustrated by the following VBScript code using ADO:

OLEDB works fine ...

Option Explicit
Dim conn
Set conn = CreateObject("ADODB.Connection")
Dim connStr
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\mdbTest.mdb"
conn.Open connStr

On Error Resume Next
conn.Execute "DROP TABLE Cheeses"
On Error GoTo 0
conn.Execute "CREATE TABLE Cheeses (Id LONG PRIMARY KEY, CheeseName TEXT(50) DEFAULT 'Cheddar')"

conn.Execute "INSERT INTO Cheeses (Id) VALUES (1)"

Dim rst
Set rst = CreateObject("ADODB.Recordset")
rst.Open "SELECT CheeseName FROM Cheeses WHERE Id = 1", conn
If rst("CheeseName").Value = "Cheddar" Then
    WScript.Echo "Success"
End If

conn.Close

... but if we change the connection string to use ODBC ...

connStr = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Users\Public\mdbTest.mdb"

... then our attempt to execute the CREATE TABLE statement fails with

Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement.

TL;DR - You can't use the DEFAULT clause in a CREATE/ALTER TABLE statement under pyodbc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!