简体   繁体   English

是否可以使用python在sqlite3中运行multible语句?

[英]Is it possible to run multible statements in sqlite3 with python?

I have more than 2 tables in an sqlite3 database. 我在sqlite3数据库中有两个以上的表。 Im trying to INSERT data into one table and update a few columns in another table. 我试图将数据插入一个表并更新另一个表中的几列。 Is that possible? 那可能吗?

I have tried to user executemany() and executescript() in many shapes and forms. 我试图以多种形状和形式使用executemany()和executioncript()。 I have recieved a bunch of error messages, and its mostly because execute will not accept my parameters. 我收到了一堆错误消息,主要是因为执行不接受我的参数。

with sqlite3.connect('database.db') as conn:
    cur = conn.cursor()
    cur.executescript("""INSERT INTO prev_users (
                                imei_prev,
                                user_id_prev,
                                start_date,
                                end_date,
                                type_prev)
                               VALUES (?,?,?,?,?);
                               UPDATE phones
                                SET owner = (?), date = (?), state = (?)
                                WHERE imei = (?);
                               """,(user['imei'], user['user_id'], user['date'], date, user['type'], "None", date, "In Progress", user['imei']))

executescript() will not accept parameters because, well, it doesn't take parameters as an argument, it only takes a "script". executescript()不接受参数,因为它不会将参数作为参数,它只需要一个“脚本”。 From the doc : 来自doc

executescript(sql_script) executescript(sql_script)

This is a nonstandard convenience method for executing multiple SQL statements at once. 这是一次执行多个SQL语句的非标准方便方法。 It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. 它首先发出一个COMMIT语句,然后执行它作为参数获取的SQL脚本。

sql_script can be an instance of str. sql_script可以是str的一个实例。

For example, it might be used for creating several tables in one script. 例如,它可能用于在一个脚本中创建多个表。

executemany() runs one sql against a sequence of parameters. executemany()针对一系列参数运行一个sql。

Neither method is the right tool for the job. 这两种方法都不适合这项工作。 You'll likely have to split it into two calls to execute() . 你可能不得不将它分成两个execute()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM