Python-MSSQL (pymssql) 设置字段Identity Column

Posted

技术标签:

【中文标题】Python-MSSQL (pymssql) 设置字段Identity Column【英文标题】:Python-MSSQL (pymssql) Set a field Identity Column 【发布时间】:2018-11-08 10:46:50 【问题描述】:

我一直在尝试在 SQL 上使用 python 将 ObjectID 设置为 Identity 列。下面的 SQL 语句适用于 Management Studio (SSMS) 并将 ObjectID 设置为 Identity 列。该代码有效,但在 SSMS 上检查表时,我没有将 ObjectID 视为 Identity 列。

以下方式适用于 python,但不会更改 SSMS 上的标识列。

    在每次执行后添加conn.commit()

    使用 python 文件阅读器运行 .sql 文件。

如图所示,在python中执行代码后,Identity列仍然为空。

代码是由 SSMS 生成的,我的目的是设置 ObjectID 字段标识列。也许有更好的方法。

代码如下:

newTableName = "A_Test_DashAutomation"
try:
    cursor.execute("""
    BEGIN TRANSACTION
    SET QUOTED_IDENTIFIER ON
    SET ARITHABORT ON
    SET NUMERIC_ROUNDABORT OFF
    SET CONCAT_NULL_YIELDS_NULL ON
    SET ANSI_NULLS ON
    SET ANSI_PADDING ON
    SET ANSI_WARNINGS ON
    COMMIT
    BEGIN TRANSACTION """)

    cursor.execute("""
    CREATE TABLE dbo.Tmp_""" + newTableName + """
        (
        SubProjectTempId bigint NULL,
        CIPNumber varchar(16) NOT NULL,
        Label nvarchar(50) NULL,
        Date_Started datetime2(7) NULL,
        Date_Completed datetime2(7) NULL,
        Status nvarchar(25) NULL,
        Shape geography NULL,
        Type varchar(2) NOT NULL,
        ProjectCode varchar(16) NULL,
        ActiveFlag int NULL,
        Category varchar(32) NULL,
        ProjectDescription varchar(64) NULL,
        UserDefined varchar(1024) NULL,
        InactiveReasonDate datetime NULL,
        FYTDBudget money NULL,
        LTDBudget money NULL,
        PeriodExpenses money NULL,
        FYTDExpenses money NULL,
        LTDExpenses money NULL,
        LTDEncumbrances money NULL,
        LTDBalance money NULL,
        FiscalYear int NULL,
        ToPeriod int NULL,
        _LastImported datetime NOT NULL,
        OBJECTID int NOT NULL IDENTITY (1, 1),
        GDB_GEOMATTR_DATA varbinary(MAX) NULL
        )  ON [PRIMARY]
         TEXTIMAGE_ON [PRIMARY]
    """)

    cursor.execute("ALTER TABLE dbo.Tmp_" + newTableName + " SET (LOCK_ESCALATION = TABLE)")

    cursor.execute("SET IDENTITY_INSERT dbo.Tmp_" + newTableName + " ON")

    cursor.execute("""
    IF EXISTS(SELECT * FROM dbo.""" + newTableName + """)
         EXEC('INSERT INTO dbo.Tmp_""" + newTableName + """ (SubProjectTempId, CIPNumber, Label, Date_Started, Date_Completed, Status, Shape, Type, ProjectCode, ActiveFlag, Category, ProjectDescription, UserDefined, InactiveReasonDate, FYTDBudget, LTDBudget, PeriodExpenses, FYTDExpenses, LTDExpenses, LTDEncumbrances, LTDBalance, FiscalYear, ToPeriod, _LastImported, OBJECTID, GDB_GEOMATTR_DATA)
            SELECT SubProjectTempId, CIPNumber, Label, Date_Started, Date_Completed, Status, Shape, Type, ProjectCode, ActiveFlag, Category, ProjectDescription, UserDefined, InactiveReasonDate, FYTDBudget, LTDBudget, PeriodExpenses, FYTDExpenses, LTDExpenses, LTDEncumbrances, LTDBalance, FiscalYear, ToPeriod, _LastImported, OBJECTID, GDB_GEOMATTR_DATA FROM dbo.""" + newTableName + """ WITH (HOLDLOCK TABLOCKX)')
    """)

    cursor.execute("SET IDENTITY_INSERT dbo.Tmp_" + newTableName + " OFF")

    cursor.execute("DROP TABLE dbo." + newTableName)

    cursor.execute("EXECUTE sp_rename N'dbo.Tmp_" + newTableName + "', N'" + newTableName + "', 'OBJECT'")

    cursor.execute("""
    ALTER TABLE dbo.""" + newTableName + """ ADD CONSTRAINT
        R1143_pk PRIMARY KEY CLUSTERED 
        (
        OBJECTID
        ) WITH( PAD_INDEX = OFF, FILLFACTOR = 75, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    """)

    cursor.execute("""
    CREATE SPATIAL INDEX SIndx ON dbo.""" + newTableName + """(Shape) USING GEOGRAPHY_AUTO_GRID
         WITH( CELLS_PER_OBJECT  = 16, STATISTICS_NORECOMPUTE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
    """)

    cursor.execute("""
    ALTER TABLE dbo.""" + newTableName + """ ADD CONSTRAINT
        g1084_ck CHECK (([Shape].[STSrid]=(4326)))
    """)

    cursor.execute("COMMIT")

    conn.commit()
    print("Object ID is set to Identify column.")

except pymssql.DatabaseError, err:
    print(str(err))

任何帮助将不胜感激。

谢谢

【问题讨论】:

您的代码对我来说工作正常,无论是使用 pymssql (v2.1.3) 还是 pyodbc (v4.0.23)。您需要创建一个 minimal reproducible example 来重现您的具体问题,然后 edit 您的问题的详细信息。 希望这看起来更好 【参考方案1】:

问题解决了。每次创建新表时 STSrid 都会发生变化,因此将这部分从 SQL 代码中删除会有所帮助。但是,我不确定空间索引是否保持不变。

干杯

cursor.execute("""
ALTER TABLE dbo.""" + newTableName + """ ADD CONSTRAINT
    g1084_ck CHECK (([Shape].[STSrid]=(4326))) """)

【讨论】:

以上是关于Python-MSSQL (pymssql) 设置字段Identity Column的主要内容,如果未能解决你的问题,请参考以下文章

得到存储过程pymssql返回值

无法使用带有 Windows 身份验证的 pymssql 进行连接

使用 PYMSSQL 通过 *** 从 SQL Server 检索数据

pymssql.connect() 错误:“自适应服务器不可用或不存在”

pymssql连接sql server报错:pymssql._pymssql.OperationalError

pymssql executemany insert valueerror