SQL使用Python无法正常插入到MS Server DB中

问题描述 投票:-3回答:1

我试图将数据插入已创建的表中。代码不会抛出任何错误,只是不会写入数据库。

我认为时间戳有问题,可能是。

如果您有任何人可以请看一下代码并提供一些指示,那就太棒了。 TIA!

干杯

import pyodbc
import datetime
import time

def connect_db():
    db = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=xxxxx\SQLEXPRESS;"
                      "Database=test;"
                      "Trusted_Connection=yes;"
                      "uid=xxx;"
                      "password=xyz")
    cursor = db.cursor()



    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    sql = "INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', %)" % (timestamp)
    cursor.execute(sql)
    db.commit()
    cursor.close()
    db.close()
python sql sql-server
1个回答
0
投票
 "INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', %)" % (timestamp)

我认为你必须在%之后添加s

"INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', '%s')" % (timestamp)
© www.soinside.com 2019 - 2024. All rights reserved.