为了账号安全,请及时绑定邮箱和手机立即绑定

Python每次插入新数据时如何自动生成不存在的主键

Python每次插入新数据时如何自动生成不存在的主键

慕田峪7331174 2022-06-28 10:32:49
我有这个 SQL 查询,但每次插入新数据时都必须更改 id,因为它是主键。如何让它在每次插入时添加一个新的未使用的主键值?我正在使用 Microsoft SQL Server Studioimport urllib.request as urllibimport socketimport pyodbcfrom datetime import datetime#Timestamp for undersøgelsetimestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')#Host info og IPhost = "www.rejseplanen.dk"dest = socket.gethostbyname(host)hdata = 'host',host,'IP:',dest#Responseheader requestrequest = urllib.Request('http://rejseplanen.dk')request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36')response = urllib.urlopen(request)rdata = response.info()#SQL Connection til local databasecon = pyodbc.connect('Driver={SQL Server Native Client 11.0};'                      'Server=DESKTOP-THV2IDL;'                      'Database=host;'                      'Trusted_Connection=yes;')cursor = con.cursor()cursor.execute('SELECT * FROM host.dbo.hosts')for row in cursor:    print(row)con.execute('INSERT INTO host.dbo.hosts (Id, ip, host, HSTS, HPKP, XContentTypeOptions, XFrameOptions, ContentSecurityPolicy, Xssprotection, Server, Timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',             (4123, host, dest, rdata['Strict-Transport-Security'], rdata['Public-Key-Pins'], rdata['X-Content-Type-Options'], rdata['X-Frame-Options'], rdata['Content-Security-Policy'], rdata['X-XSS-Protection'], rdata['Server'], timestamp))con.commit()
查看完整描述

1 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

你没有。你让数据库来做。因此,主机表应定义为:


create table host (

    id int identity(1, 1) primary key,

    ip . . . 

);

然后,您将值排除在外insert:


INSERT INTO host.dbo.hosts (ip, host, HSTS, HPKP, XContentTypeOptions, XFrameOptions, ContentSecurityPolicy, Xssprotection, Server, Timestamp)

    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

(请注意,id不在列列表中。)


查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 158 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号