python 连接mysql相关
解决需要sudo才能登陆mysql的问题:
https://blog.csdn.net/m0_46278037/article/details/113923726
Python连接mysql(pandas):原作者:https://zhuanlan.zhihu.com/p/72347359
以下内容为搬运,方便自己看的
pip install pandas
pip install sqlalchemy
pip install pymysql
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接
# 按实际情况依次填写MySQL的用户名、密码、IP地址、端口、数据库名
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/dbname')
# MySQL导入DataFrame
# 填写自己所需的SQL语句,可以是复杂的查询语句
sql_query = 'select * from tbname;'
# 使用pandas的read_sql_query函数执行SQL语句,并存入DataFrame
df_read = pd.read_sql_query(sql_query, engine)
print(df_read)
'''like this:
id pid name
0 1 0 JS
1 2 1 js
2 3 1 ab
3 4 0 AB
4 5 4 Q
5 6 4 QQ
'''
# DataFrame写入MySQL
# 新建DataFrame
df_write = pd.DataFrame({'id': [10, 27, 34, 46], 'name': ['张三', '李四', '王五', '赵六'], 'score': [80, 75, 56, 99]})
# 将df储存为MySQL中的表,不储存index列
df_write.to_sql('testdf', engine, index=False)
""" like this:
mysql> select * from testdf;
+------+------+-------+
| id | name | score |
+------+------+-------+
| 10 | aaa | 80 |
| 27 | bb | 75 |
| 34 | ccc | 56 |
| 46 | dd | 99 |
+------+------+-------+
4 rows in set (0.00 sec)
"""
还有一个大佬写的代码实例:https://github.com/xiaofeipapa/python_example
游标是用来执行sql语句的,查询的结果集也会保存在游标之中
#! /usr/bin/python
# -*- coding: UTF-8 -*-
"""
作者: 小肥巴巴
简书: https://www.jianshu.com/u/db796a501972
邮箱: imyunshi@163.com
github: https://github.com/xiaofeipapa/python_example
您可以任意转载, 恳请保留我作为原作者, 谢谢.
"""
import pymysql
host = 'localhost'
port = 3306
db = 'testdb'
user = 'root'
password = '123456'
# ---- 用pymysql 操作数据库
def get_connection():
conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password)
return conn
def check_it():
conn = get_connection()
# 使用 cursor() 方法创建一个 dict 格式的游标对象 cursor
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 使用 execute() 方法执行 SQL 查询
cursor.execute("select count(id) as total from dbtest")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("-- 当前数量: %d " % data['total'])
# 关闭数据库连接
cursor.close()
conn.close()
if __name__ == '__main__':
check_it()
sql注入例如where username=‘A’ or 1=1;
sql预编译可以避免sql注入,如下,将sql和参数分开来避免问题发生
# 新增单条记录
def create_one():
with UsingMysql(log_time=True) as um:
sql = "insert into Product(name, remark) values(%s, %s)"
params = ('男士双肩背包1', '这个是非常好的背包')
um.cursor.execute(sql, params)
# 查看结果
select_one(um.cursor)
数据库连接池:预先创建一些数据库连接,缓存起来,避免了程序反复连接和销毁的操作