1.安装PyMySQL 扩展python
pip3 install PyMySQLmysql
2.连接mysql数据库sql
import pymysql # 开发数据库链接 db = pymysql.connect('127.0.0.1','root','','python') # 使用cursor()方法建立一个游标对象cursor cursor = db.cursor() # 使用execute() 方法进行sql查询 cursor.execute('select * from py_mysql') # 使用fetchone()方法获取单挑数据 data = cursor.fetchone() print(data) # 关闭链接 cursor.close() db.close()
3.建立数据表数据库
import pymysql # 打开数据库链接 db = pymysql.connect('127.0.0.1','root','','python') # 使用 cursor() 方法建立一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL,若是表存在则删除 cursor.execute('drop table if exists py_create_mysql') # 使用预处理语句建立表 sql = """create table py_create_mysql ( id int unsigned primary key auto_increment, username char(32) default '', age tinyint unsigned default 0, created_at timestamp )""" cursor.execute(sql) # 关闭数据库连接 cursor.close()
4.插入一条数据fetch
import pymysql # 打开数据库链接 db = pymysql.connect("127.0.0.1", "root", "", "python") # 使用cursor()方法获取操做游标 cursor = db.cursor() # sql 插入语句 sql = "insert into py_create_mysql(username,age,created_at) values('%s','%d','%s')"%('liuhaizhuang',25,'2018-2-1 12:12:12') try: # 执行sql语句 cursor.execute(sql) # 执行sql语句 db.commit() except: # 发生错误 回滚 db.rollback() # 关闭连接 db.close()
5.查询数据对象
import pymysql # 连接 db = pymysql.connect('127.0.0.1','root','','python') # cursor() cursor = db.cursor() # 查询sql sql = "select * from py_create_mysql where id>='%d'"%(1) try: # 执行sql语句 cursor.execute(sql) # 获取一条记录 #dataOne = cursor.fetchone() # 查询所有数据 dataAll = cursor.fetchall() # 打印单条结果 #print(dataOne[0],dataOne[1],dataOne[2]) # 打印多条结果集 print(dataAll) except: print('data error') # 关闭数据库连接 db.close()