1、安装pymysql
pip install pymysql
2、获取链接对象
from pymysql import Connection
# 构建到mysql数据库的链接
conn = Connection(
host="localhost",
port=3306,
user="root",
password="123456"
)
#关闭链接
conn.close()
3、执行SQL查询
通过链接对象调用cursor()方法,得到游标对象
4、总结
from pymysql import Connection
# 构建到mysql数据库的链接
conn = Connection(
host="localhost",
port=3306,
user="root",
password="123456"
)
# print(conn.get_server_info())
# 执行非查询性质的SQL
# 获取到游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("student")
# 执行sql语句
# cursor.execute("create table student(id int);")
# 执行查询性质的SQL
cursor.execute("select * from course;")
results = cursor.fetchall()
for r in results:
print(r)
# 关闭链接
conn.close()
5、python操作mysql数据插入
- 方法一,使用commit确认
from pymysql import Connection
# 构建到mysql数据库的链接
conn = Connection(
host="localhost",
port=3306,
user="root",
password="123456"
)
# print(conn.get_server_info())
# 执行非查询性质的SQL
# 获取到游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("student")
# 执行插入sql语句
cursor.execute("insert into course values(7,'ff','dd')")
# 通过commit确认
conn.commit()
# 关闭链接
conn.close()
- 方法二,构建对象时,设置自动commit的属性 autocommit=True
from pymysql import Connection
# 构建到mysql数据库的链接
conn = Connection(
host="localhost",
port=3306,
user="root",
password="123456",
autocommit=True
)
# print(conn.get_server_info())
# 执行非查询性质的SQL
# 获取到游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("student")
# 执行插入sql语句
cursor.execute("insert into course values(8,'ff','dd')")
# 关闭链接
conn.close()
6、从文件中读取数据,并写入数据库中
- 读取数据
- 封装数据对象
- 构建数据库链接
- 写入数据库
from pymysql import Connection
from data_define import Record
from fine_define import TextFileReader
text_file = TextFileReader("D:/1研究生学习/python.txt")
text_data:list[Record]=text_file.read_data()
print(text_data)
# 构建到mysql数据库的链接
conn = Connection(
host="localhost",
port=3306,
user="root",
password="123456",
autocommit=True
)
# print(conn.get_server_info())
# 执行非查询性质的SQL
# 获取到游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("student")
# 组织sql语句
for r in text_data:
sql=f"insert into course(cno,cname,dept)"\
f"values('{r.cno}','{r.cname}','{r.dept}')"
#执行sql语句
cursor.execute(sql)
# 关闭链接
conn.close()