pyodbc - add column to MS Access with default value

后端 未结 1 1848
野的像风
野的像风 2021-01-25 09:47

I\'m trying to add a column to an MS Access database table using pyodbc and Python 3.5.

Using the expression

self.cursor.execute(\"ALTER TABLE data ADD C         


        
相关标签:
1条回答
  • 2021-01-25 10:45

    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.

    0 讨论(0)
提交回复
热议问题