Search code examples
pythonpymssql

How can I create multiple connections with pymssql?


I am trying to create a table via pymssql, but I am getting the error:

InterfaceError: Connection is closed.

I have already tried to put the CREATE TABLE statement into the same connection with the SELECT statement, but when I did this no Table was created.

Somebody got a workaround for this?

Here is my code:

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)

Solution

  • See below, I removed your conn.close() function

    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)