20位python Long Int进入Numeric(24,0)列的MSSQL'数值超出范围'错误

时间:2019-01-03 18:14:46

标签: python sql-server pypyodbc

我正在尝试将20位64位python长整数插入MSSQL Numeric(24,0)列。这会导致MSSQL出现“数值超出范围”错误。我正在使用pypyodbc模块和SQL Server的ODBC驱动程序13从我的python应用程序插入数据。

我尝试在SQL中使用Numeric(38,0)列只是为了测试限制,但收到相同的错误。在插入语句中,我还尝试将ID显式转换为Numeric(24,0)数据类型。所有尝试均导致相同的错误。

#Python SQL Insert Code
id = 'ADD7A9FA-E77B-4BBB-92AA-3D9C7BBB44D0'
idlist =  id.split('-')

val = [int(idlist[0] + idlist[1] + idlist[2], 16), 
int(idlist[3] + idlist[4], 16)]

cmd = "INSERT INTO jssuser.dbo.API_VIMSPost (\
[id_int1], \
[id_int2]) \
VALUES (?, ?)"

#function to simplify the use of pypyodbc
sqlcmd.sqlCmd(cmd, values = val)

#SQL Table Code
USE [jssuser]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[API_VIMSPost](
    [id_int1] [numeric](24, 0) NOT NULL,
    [id_int2] [numeric](24, 0) NOT NULL,
 CONSTRAINT [PK_PostID] PRIMARY KEY CLUSTERED 
(
    [id_int1] ASC,
    [id_int2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = 
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

我希望20位和64位的python long int将适合Numeric(20,0)或更大类型的MSSQL列。但是,插入会导致“数值超出范围”错误。

1 个答案:

答案 0 :(得分:0)

Python整数值的大小仅受可用内存限制;它们不限于任意位数。但是,SQL Server ODBC驱动程序可以处理的最大整数值为(64位有符号)bigint,其最大正值为math.pow(2, 63) - 19223372036854775807,即19 (19)位数。

当pypyodbc尝试传递20位整数时,ODBC驱动程序对此进行了扼制,因此失败了

x = 13807673592980537824
crsr.execute("CREATE TABLE ##tmp (id INT PRIMARY KEY, id_int1 NUMERIC(24, 0))")
sql = "INSERT INTO ##tmp (id, id_int1) VALUES (?, ?)"
params = (1, x)
crsr.execute(sql, params)

但是,以下方法可行,因为pypyodbc不会告诉ODBC驱动程序期望整数

x = 13807673592980537824
crsr.execute("CREATE TABLE ##tmp (id INT PRIMARY KEY, id_int1 NUMERIC(24, 0))")
sql = "INSERT INTO ##tmp (id, id_int1) VALUES (?, ?)"
params = (1, Decimal(x))  # convert Python `int` to Python `decimal.Decimal`
crsr.execute(sql, params)