【问题标题】:How can I create multiple connections with pymssql?如何使用 pymssql 创建多个连接?
【发布时间】:2019-10-17 13:24:05
【问题描述】:

我正在尝试通过 pymssql 创建表,但出现错误:

InterfaceError: 连接已关闭。

我已经尝试将 CREATE TABLE 语句与 SELECT 语句放在同一个连接中,但是当我这样做时,没有创建任何表。

有人有解决办法吗?

这是我的代码:

from bs4 import BeautifulSoup as bs
import re
from collections.abc import Iterable
import pymssql


conn = pymssql.connect(
    host='xxxx',
    port=xxx,
    user='xxxx',
    password='xxxx',
    database='xxxx'
)
cursor = conn.cursor() 
cursor.execute('SELECT xxx FROM xxx')

text = cursor.fetchall()


conn.close()

c1 = conn.cursor()
c1.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
"""
          )
conn.close()

raw = []  
raw.append(text)
raw1 = str(raw)
soup = bs(raw1, 'html.parser')
autor = soup.get_text()

clear = []
s = autor.replace('\\n', '')
clear.append(s)

print (clear)

【问题讨论】:

  • conn.close() 关闭连接,因此您的查询不起作用。您要么需要重新建立连接,要么打开另一个
  • 所以我不能把 SELECT 语句和 CREATE 语句放在同一个连接中?
  • 你可以没有问题,只是不要关闭连接

标签: python pymssql


【解决方案1】:

见下文,我删除了你的 conn.close() 函数

从 bs4 导入 BeautifulSoup 作为 bs 重新进口 从 collections.abc 导入 Iterable 导入pymssql

conn = pymssql.connect(
    host='xxxx',
    port=xxx,
    user='xxxx',
    password='xxxx',
    database='xxxx'
)
cursor = conn.cursor() 
cursor.execute('SELECT xxx FROM xxx')

text = cursor.fetchall()


#conn.close() 

c1 = conn.cursor()
c1.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
"""
          )
conn.close()

raw = []  
raw.append(text)
raw1 = str(raw)
soup = bs(raw1, 'html.parser')
autor = soup.get_text()

clear = []
s = autor.replace('\\n', '')
clear.append(s)

print (clear)

【讨论】:

  • 我认为他也应该删除第一个conn.close()。此外,在 Python 中,您使用 # 注释一行,而不是 //
  • @ChristianCavuti 我的错,我仍然处于 JavaScript 模式!是的,根据我的评论,我确实是指第一个 conn.close()
【解决方案2】:

当您使用任何连接器管理连接时,当您关闭连接并想要执行另一个查询时,您需要以类似的方式创建一个新连接:

conn = pymssql.connect(
    host='xxxx',
    port=xxx,
    user='xxxx',
    password='xxxx',
    database='xxxx'
)
cursor = conn.cursor() 
cursor.execute('SELECT xxx FROM xxx')
text = cursor.fetchall()
conn.close()
conn = pymssql.connect(
    host='xxxx',
    port=xxx,
    user='xxxx',
    password='xxxx',
    database='xxxx'
)
cursor = conn.cursor()
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
"""
)
conn.close()

无论如何,管理与数据库的连接并不是最佳做法,因此使用连接池是一种很好的做法。不幸的是,pymssql 没有内部连接池机制,但您可以通过 SQLAlchemy 实现它,找到 here 的文档来做到这一点:

【讨论】:

  • 感谢克里斯蒂安的回答。我不再收到错误消息,但是 CREATE 语句没有在数据库中创建新表。
猜你喜欢
  • 2012-04-12
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多