Python与MySQL的交互

Python与MySQL的交互

1 、安装mysql模块

pip3 install pymysql

2 、connection 对象

用于建立与数据库的连接

2.1  创建对象

conn = connection(参数列表)

2.1.1 参数列表

  1. host:连接的mysql主机,如果本机是'localhost'
  2. port:连接的mysql主机的端口,默认是3306
  3. db:数据库的名称
  4. user:连接的用户名
  5. password:连接的密码
  6. charset:通信采用的编码方式,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码 对象的方法
import pymysql
# 获取一个数据库连接
connection =  pymysql.connect(host='192.168.242.128',port=3306,user='root',password='123456',db='test1',charset='utf8')
#获取和数据库交互的对象
cursor = connection.cursor()
# 要执行的sql
sql = 'select * from emp'
# 获取Ssql 执行后的数据
cursor.execute(sql)
result = cursor.fetchall()
for res in result:
    print(res)

 

posted @ 2018-03-06 13:08  嗡嗡小蜜蜂  阅读(149)  评论(0编辑  收藏  举报