python连接mysql

import MySQLdb
import time


class MysqlSearch(object):
def __init__(self):
self.get_conn()

def get_conn(self):
# 获取连接
try:
self.conn = MySQLdb.connect(
host='192.168.xx.xxx',
user='xxx',
password='xxx',
db='xxx',
port=3306,
charset='utf8'
)
except MySQLdb.Error as e:
print('Error: %s' % e)

# 关闭连接
def close_conn(self):
try:
if self.conn:
self.conn.close()
except MySQLdb.Error as e:
print('Error: %s' % e)

# 获取连接
def get_one(self):
self.get_conn()
# 准备sql
sql = 'select * from logger ORDER BY gmt_create DESC'
time.sleep(2)
# 找到cursor
cursor = self.conn.cursor()
# 执行sql
cursor.execute(sql)
# 拿到结果
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall()][0] # 查询多条
dxinfo = rest['information']
dxyzm = dxinfo[12:18] # 切片(截取短信验证码)
# 关闭cursor/连接
# cursor.close()
return dxyzm



def main():
obj = MysqlSearch()
obj.update_time()


if __name__ == '__main__':
main()
原文地址:https://www.cnblogs.com/huaegg/p/13614297.html