python操作mysql(3)--链接数据库

 1 import pymysql
 2 
 3  
 4 
 5 # 打开数据库连接(ip/端口/数据库用户名/登录密码/数据库名/编码)
 6 
 7 db = pymysql.connect(host="localhost",port=3306,user="root", password="root",db= "test",charset='utf8')
 8 
 9 # 使用 cursor() 方法创建一个游标对象 cursor
10 
11 cursor = db.cursor()
12 
13  
14 
15 # 使用 execute()  方法执行 SQL 查询(查询mysql的版本)
16 
17 cursor.execute("SELECT VERSION()")
18 
19 # 使用 fetchone() 方法获取单条数据.
20 
21 data = cursor.fetchone()
22 
23 print("Database version : %s " % data)
24 
25  
26 
27 # 关闭数据库连接
28 
29 db.close()
原文地址:https://www.cnblogs.com/jayson-0425/p/9920576.html