20171031 python访问MySQL

2017-10-31  本文已影响10人  李绍俊

1. 基本流程

Paste_Image.png

2. 连接到数据库

Paste_Image.png

3. connection对象的方法

Paste_Image.png

4. cursor对象的方法

Paste_Image.png

5. 通用的示例代码

# -*- coding: utf-8 -*-
# @Time    : 2017/10/31 13:43
# @Author  : 李绍俊
# @Email   : 188792829@qq.com
# @File    : testMySQL.py


import MySQLdb as con

cnx = con.connect(host = 'localhost',
                  port = 3306,
                  user='root',
                  passwd='supermap',
                  database='test03',
                  charset = 'utf8')

cur = cnx.cursor()

tbName = '员工表'

try:
    cur.execute(f"drop table if EXISTS {tbName}")
    cur.execute(f"create table {tbName}(编号 varchar(10), b int, c int)")



    for i in range(200):
        strSQL = f"insert into {tbName} values('中文测试',{i},{i})"
        cur.execute(strSQL)

    cnx.commit()
except Exception as e:
    print(e)
    cnx.rollback()


cur.execute(f"select * from {tbName}")

# for row in cur.fetchall():
#     print(row)

print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())

print(cur.fetchmany(3))

print(cur.fetchall())

cur.close()

cnx.close()

上一篇下一篇

猜你喜欢

热点阅读