Python connection to SQL Server database - pymssql usage basis

Install

pip install pymssql


Connect to the database

The way pymssql connects to the database is basically the same as using sqlite:

  • connectCreate a connection object using
  • connect.cursorCreate a cursor object, and the execution of SQL statements is basically carried out on the cursor
  • cursor.executeXXXMethods execute SQL statements, cursor.fetchXXXget query results, etc.
  • Call closemethod to close cursor cursorand database connection
import pymssql

# server    数据库服务器名称或IP
# user      用户名
# password  密码
# database  数据库名称
conn = pymssql.connect(server, user, password, database)

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)
)
""")
cursor.executemany(
    "INSERT INTO persons VALUES (%d, %s, %s)",
    [(1, 'John Smith', 'John Doe'),
     (2, 'Jane Doe', 'Joe Dog'),
     (3, 'Mike T.', 'Sarah H.')])
# 如果没有指定autocommit属性为True的话就需要调用commit()方法
conn.commit()

# 查询操作
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
row = cursor.fetchone()
while row:
    print("ID=%d, Name=%s" % (row[0], row[1]))
    row = cursor.fetchone()

# 也可以使用for循环来迭代查询结果
# for row in cursor:
#     print("ID=%d, Name=%s" % (row[0], row[1]))

# 关闭连接
conn.close()

Note : The parameters of the query operation in the example are %snot used '%s'. If the parameter value is a string , single quotes will be automatically added when the statement is executed.

Notes on using cursors

A query with only one cursor at a time can be active for a connection, as follows:

c1 = conn.cursor()
c1.execute('SELECT * FROM persons')

c2 = conn.cursor()
c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')

print( "all persons" )
print( c1.fetchall() )  # 显示出的是c2游标查询出来的结果

print( "John Doe" )
print( c2.fetchall() )  # 不会有任何结果

In order to avoid the above problems, the following two methods can be used:

  • Create multiple connections to ensure that multiple queries can be executed in parallel on cursors on different connections
  • Use the fetchallmethod to obtain the cursor query result before executing the next query, as follows:
c1.execute('SELECT ...')
c1_list = c1.fetchall()

c2.execute('SELECT ...')
c2_list = c2.fetchall()

Cursor returns behavior dictionary variable

In the above example, each row of the query result obtained by the cursor is a tuple type. You can make the cursor return a dictionary variable
by specifying parameters when creating the cursor . The key in the dictionary is the column name of the data table.as_dict

conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor(as_dict=True)

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
    print("ID=%d, Name=%s" % (row['id'], row['name']))

conn.close()

Using withStatements (Context Managers)

withIt is possible to omit the explicit call method by using the statement to closeclose the connection and the cursor

with pymssql.connect(server, user, password, database) as conn:
    with conn.cursor(as_dict=True) as cursor:
        cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

call stored procedure

Versions above pymssql 2.0.0 can call stored procedures through cursor.callprocmethods

with pymssql.connect(server, user, password, database) as conn:
    with conn.cursor(as_dict=True) as cursor:
        # 创建存储过程
        cursor.execute("""
        CREATE PROCEDURE FindPerson
            @name VARCHAR(100)
        AS BEGIN
            SELECT * FROM persons WHERE name = @name
        END
        """)

        # 调用存储过程
        cursor.callproc('FindPerson', ('Jane Doe',))
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

Reference link:  http://pymssql.org/en/stable/pymssql_examples.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324962534&siteId=291194637