Python链接MySQL之Python库pymysql

 链接数据库

pymysql链接数据库的方式和使用sqlite的方式基本相同:python

  • 使用connect建立链接对象
  • connect.cursor建立游标对象,SQL语句的执行基本都在游标上进行
  • cursor.executeXXX方法执行SQL语句,cursor.fetchXXX获取查询结果等
  • 调用close方法关闭游标cursor和数据库链接
import pymssql # server 数据库服务器名称或IP # user 用户名 # password 密码 # database 数据库名称 conn = pymssql.connect(server, user, password, database) cursor = conn.cursor()

新建、插入操做mysql

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 INFO 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()

查询操做sql

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()

游标使用注意事项

一个链接一次只能有一个游标的查询处于活跃状态,以下:数据库

c1 = conn.cursor()
c1.execute('SELECT * FROM persons')
c2 = conn.cursor()
c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
print("all person")
print(c1.fetchall()) # 显示出的是c2游标查询出来的结果
print("John Doe")
print(c2.fetchall()) # 不会有任何显示

为了不上述的问题能够使用如下两种方式:服务器

  • 建立多个链接来保证多个查询能够并行执行在不一样链接的游标上
  • 使用fetchall方法获取到游标查询结果以后再执行下一个查询,以下:
c1.execute('SELECT ...')
c1_list = c1.fetchall()
c2.execute('SELECT ...')
c2_list = c2.fetchall()

游标返回行为字典变量

上述例子中游标获取的查询结果每一行为元祖类型,能够经过在建立游标时指定as_dict参数来使游标返回字典变量。fetch

字典中的键为数据表的列名spa

import pymysql

conn = pymysql.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()

使用with语句(上下文管理器)

能够经过使用with语句来省去显示的调用close方法关闭链接和游标code

with pymysql.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']))

调用存储过程

pymysql 2.0.0以上的版本能够经过cursor.callproc方法来调用存储过程server

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']))
相关文章
相关标签/搜索