连接mysql数据库

 1 import pymysql
 2 class Mydb(object):
 3     def __init__(self,host,user,passwd,db,port=3306,charset='utf8'):
 4         try:
 5             self.coon = pymysql.connect(
 6                 host = host,
 7                 user = user,
 8                 passwd = passwd,
 9                 db = db,
10                 port = port,
11                 charset = charset,
12                 autocommit = True #自动提交
13             )
14         except Exception as e:
15             print('连接数据库失败!%s'%e)
16         else:
17             self.cur = self.coon.cursor(cursor=pymysql.cursors.DictCursor)
18     def ex_sql(self,sql):
19         try:
20             self.cur.execute(sql)
21         except Exception as error:
22             print('sql语句错误!%s'%error)
23         else:
24             self.res = self.cur.fetchall()
25             return self.res
26 
27 my = Mydb('localhost','','','','')
28 my.ex_sql('select * from test;')
人生的旅途,前途很远,也很暗。然而不要怕,不怕的人的面前才有路。
原文地址:https://www.cnblogs.com/ymany/p/9071953.html