【问题标题】:Why does with statement work with sqlite3 but not with mysql.connection?为什么 with 语句适用于 sqlite3 但不适用于 mysql.connection?
【发布时间】:2020-07-28 12:11:00
【问题描述】:

当我运行以下代码时:

with sqlite3.connect("example.db") as con:
    c=con.cursor()
    c.execute("CREATE TABLE test (id,name) ")

一切正常。

但是当我使用mysql.connector:

import mysql.connector as mariadb

with mariadb.connect(user='root', password='root', database='publications') as con:
    c = con.cursor()
    c.execute("CREATE TABLE test (id INT,name VARCHAR(45))")

我收到此错误:

File "<...>", line 4, in <module>
with mariadb.connect(user='root', password='root', database='publications') as con:
AttributeError: __enter__

谁能告诉我这是什么原因?正如我在"PEP 343 -- The "with" Statement" 中读到的,要使用带有with 语句的对象,您需要实现__enter__()__exit__() 方法。所以它似乎是在sqlite3 中实现的,但不是在mysql.connection 中实现的。但这是什么原因呢?是否有更深层次的原因或Mysql 只是没有实现它?

谢谢你:)

【问题讨论】:

  • 在 MySQL/MariaDB 中指定列数据类型是强制性的。
  • 如果我没记错的话,WITH 是在 MySQL 8 中添加的。这是你的吗?

标签: python mysql sqlite with-statement


【解决方案1】:

在 SQLite 中,列没有类型(默认类型)。在 MySQL 中,列需要有一个明确的类型。添加类型和解决的问题。

例如,SQL 语句可能是这样的:

CREATE TABLE test (id int, name varchar(50))

【讨论】:

  • 对不起,这是示例代码中的错误,让我困惑的实际错误已经发生在with语句的行中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2021-04-09
  • 2014-03-31
  • 2018-06-26
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多