使用mysqlclient
先安装mysqlclient
网址:https://pypi.org/project/mysqlclient/
python中可使用pip安装,pip install mysqlclient
也可以使用别的方法,详细可查看之前的文章:
爬取百度百科词条写入数据库
python操作mysql
查询数据
1 | import MySQLdb |
可能会出现异常,所以改写1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import MySQLdb
try:
# 获取连接
connection = MySQLdb.connect(
host = 'localhost',
user = 'root',
password = 'password',
db = 'school',
charset = 'utf8mb4',
port = 3306 # 默认3306,可不填port
)
# 获取数据
cursor = connection.cursor()
cursor.execute('SELECT * FROM `students`ORDER BY `in_time`DESC;')
result = cursor.fetchone() # 获取第一条数据
print (result)
except MySQLdb.Error as e:
print('Error : %s ' % e)
finally:
# 关闭连接
connection.close()
因为这个操作是所有都有的,所以封装成一个对象
1 | import MySQLdb |
** 补充(分页查询):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def get_more_by_pages(self, page, page_size):
# 分页查询数据
offset = (page -1) * page_size
cursor = self.connection.cursor()
sql = 'SELECT * FROM `students`WHERE`name`=%s ORDER BY `in_time`DESC LIMIT %s , %s;'
cursor.execute(sql,('weilai', offset, page_size))
result = [dict(zip([k[0] for k in cursor.description],row))
for row in cursor.fetchall()]
# print(result)
# [{'id': 7, 'name': 'weilai', 'nickname': 'imwl', 'sex': '男', 'in_time': datetime.datetime(2018, 12, 27, 22, 5, 41)},
# {'id': 8, 'name':'weilai', 'nickname': 'imwl', 'sex': '男', 'in_time': datetime.datetime(2018, 12, 27, 22, 5, 41)},
# {'id': 9, 'name': 'weilai', 'nickname': 'imwl', 'sex': '男', 'in_time': datetime.datetime(2018, 12, 27, 22, 5, 41)}]
cursor.close()
self.close_connection()
return result
新增/修改数据到数据库
出现问题不应该提交
1 | def add_one(self): |