mysql与python交互
Python 中操作 MySQL 步骤
安装包:
pip install pymysql
引入模块
- 在py文件中引入pymysql模块
from pymysql import *
Connection 对象
-
用于建立与数据库的连接
-
创建对象:调用connect()方法
conn=connect(参数列表)
- 参数host:连接的mysql主机,如果本机是'localhost'
- 参数port:连接的mysql主机的端口,默认是3306
- 参数database:数据库的名称
- 参数user:连接的用户名
- 参数password:连接的密码
- 参数charset:通信采用的编码方式,推荐使用utf8
对象的方法
- close()关闭连接
- commit()提交
- rollback()回滚
- cursor()返回Cursor对象,用于执行sql语句并获得结果
Cursor对象
- 用于执行sql语句,使用频度最高的语句为select、insert、update、delete
- 获取Cursor对象:调用Connection对象的cursor()方法
cs1=conn.cursor()
对象的方法
- close()关闭
- execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
- fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
- fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
对象的属性
- rowcount只读属性,表示最近一次execute()执行后受影响的行数
- connection获得当前连接对象
插入一条数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from pymysql import Connection 2 3 4 5 class ConnectMysql(object): 6 def __init__(self): 7 # 连接数据库 8 self.conn = Connection(host='localhost', port=3306, user='root', password='mysql', database='python', charset='utf8') 9 # 获取cursor对象 10 self.cs = self.conn.cursor() 11 12 def run(self): 13 """""" 14 try: 15 # 插入数据 16 count = self.cs.execute('insert into classes(name) values(%s)', ['py666']) 17 except Exception as e: 18 print(e) 19 else: 20 print(count) 21 self.conn.commit() 22 23 def __del__(self): 24 self.cs.close() 25 self.conn.close() 26 27 if __name__ == '__main__': 28 conn = ConnectMysql() 29 conn.run()
查询一条数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from pymysql import Connection 2 3 4 class ConnectionMysql(object): 5 """""" 6 def __init__(self): 7 """""" 8 self.conn = Connection(host='localhost', port=3306, user='root', password='mysql', database='python', charset='utf8') 9 self.cs = self.conn.cursor() 10 11 def run(self): 12 """""" 13 try: 14 count = self.cs.execute('select * from goods where id = 1') 15 except Exception as e: 16 print(e) 17 else: 18 print(count) 19 res = self.cs.fetchone() 20 print(res) 21 22 def __del__(self): 23 """""" 24 self.cs.close() 25 self.conn.close() 26 27 28 if __name__ == '__main__': 29 conn = ConnectionMysql() 30 conn.run()
查询多条数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from pymysql import Connection class ConnectionMysql(object): """""" def __init__(self): """""" self.conn = Connection(host='localhost', port=3306, user='root', password='mysql', database='python', charset='utf8') self.cs = self.conn.cursor() def run(self): """""" try: count = self.cs.execute('select * from goods') except Exception as e: print(e) else: print(count) # 获取多条数据的方法 res = self.cs.fetchall() # 列表生成式 打印 print([x[1] for x in res]) def __del__(self): """""" self.cs.close() self.conn.close() if __name__ == '__main__': conn = ConnectionMysql()
参数化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from pymysql import Connection class ConnectionMysql(object): """""" def __init__(self): """""" self.conn = Connection(host='localhost', port=3306, user='root', password='mysql', database='python', charset='utf8') self.cs = self.conn.cursor() def run(self): """""" try: params = [3] count = self.cs.execute('select * from goods where id = %s', params) # 注意 如果参数中有多个值时,,需要使用多个%s 或%d except Exception as e: print(e) else: print(count) # 获取多条数据的方法 res = self.cs.fetchall() # 列表生成式 打印 print([x[1] for x in res]) def __del__(self): """""" self.cs.close() self.conn.close() if __name__ == '__main__': conn = ConnectionMysql() conn.run()