每天一篇python之第一天python连接mysql执行查询

每天一篇python之第一天python连接mysql执行查询

 

 

=============================================

环境:

windows10

eclipse4.5.0

python3.5

PyMySQL (0.7.11)

==============================================

1.windows10  eclipse4.5.0  python3.5  安装省略

2.安装PyMySQL:pip install PyMySQL

3.编写代码:

 1 #导入pymysql.cursors模块
 2 import pymysql.cursors
 3 
 4 #连接数据库
 5 connection = pymysql.connect(
 6   host = 'ip',
 7   port = 端口,
 8   user = '用户',
 9   password = '密码',
10   db = '数据库',
11   charset = 'utf8',
12   cursorclass=pymysql.cursors.DictCursor
13 )
14 
15 try:
16   #使用cursor()方法获取游标对象
17   cursor = connection.cursor()
18   print(cursor)
19 
20   #定义sql语句
21   sql = 'select host,user,password from mysql.user;'
22   #执行sql语句
23   cursor.execute(sql)
24   #sql语句输出结果赋予result
25   result = cursor.fetchall()
26   #输出结果
27   for i in range(len(result)):
28     print(i,result[i]['user'],result[i]['host'],result[i]['password'])
29 
30 finally:
31   #关闭连接,否则会消耗应用及mysql资源
32   connection.close()

结果贴图:

 

 

转载请标注原文出处:http://www.cnblogs.com/chenjw-note/articles/6901585.html

posted @ 2017-05-24 23:34  chenjianwen  阅读(503)  评论(0编辑  收藏  举报