在python文件中使用Sqlite3命名变量

2024-05-03 09:03:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用当前日期命名数据库文件,以便在运行时创建一个以当前日期命名的数据库文件。到目前为止,我得到的是:

import sqlite3
import time


timedbname = time.strftime("%d/%m/%Y")

# Connecting to the database file
conn = sqlite3.connect(???)

此错误与“%d/%m/%Y”中的“/”或“-”或“.”相同:

^{pr2}$

Tags: 文件thetoimport数据库timeconnectconn
3条回答

成功了:

import sqlite3
import time


timedbname = time.strftime("_" + "%d.%m.%Y")
conn = sqlite3.connect(timedbname + '.db')

表名中不能有破折号。也不能以数字开头。在

import sqlite3
from datetime import date

timedbname = '_' + str(date.today()).replace('-','_')

# Connecting to the database file
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE %s (col1 int, col2 int)''' % (timedbname))
cursor.execute('''INSERT INTO %s VALUES (1, 2)''' % (timedbname))
cursor.execute('''SELECT * FROM %s'''%timedbname).fetchall()

尝试使用:

time.strftime("%d-%m-%Y")

我想它不起作用是因为生成的日期中有斜杠。在

相关问题 更多 >