Python课程笔记(十)
不陌生,之前学习一个开源SpringBoot项目,Mysql5.5更换到5.7搞得头疼。
数据库连接的坑之前写的IDEA系列连接会遇到的问题。课程代码
今天上课就主要学习了python如何连接mysql及增删改查操作,曾经写过Java项目,这里大同小异,就很简单了。
一、SQLite
SQLite数据库是一个关系型数据库,常作为嵌入式数据库内嵌在应用程序中。
方法 | 说明 |
---|---|
sqlite3.connect(database[,timeout, other optional argument]) | 连接到一个SQLite数据库文件。若不存在则创建 |
connection.cursor([cursorClass]) | 创建一个游标cursor |
cursor.execute(sql[, optional parameters]) | 执行SQL命令的语句 |
connection.execute(sql[, optional parameters]) | 执行SQL命令的语句 |
connection.commit() | 提交事务 |
connection.close() | 关闭数据库连接 |
将你和5位同学的姓名、专业、年龄、籍贯数据保存成为sqlite格式test.db磁盘文件,并将这6条记录显示到屏幕上。
创建test.db文件,建表(user),并插入数据:(数据纯属瞎编)
import sqlite3
conn = sqlite3.connect("d:/test.db")
sqlstr = "create table user (name varchar(5) primary key, profession varchar(10), age varchar(5), hometown varchar (25))"
conn.execute(sqlstr)
print("create table successfully")
cur = conn.cursor()
sqlstr1 = "insert into user(name, profession, age, hometown)values('王哲铭', '信息工程',20,'湖北十堰') "
cur.execute(sqlstr1)
sqlstr2 = "insert into user(name, profession, age, hometown)values('肖战', '汉语言学',22,'湖北武汉') "
cur.execute(sqlstr2)
sqlstr3 = "insert into user(name, profession, age, hometown)values('蔡徐坤', '英语翻译',18,'湖北恩施') "
cur.execute(sqlstr3)
sqlstr4 = "insert into user(name, profession, age, hometown)values('王一博', '教育技术',25,'湖北仙桃') "
cur.execute(sqlstr4)
sqlstr5 = "insert into user(name, profession, age, hometown)values('罗志祥', '美容美发',16,'湖北襄阳') "
cur.execute(sqlstr5)
sqlstr6 = "insert into user(name, profession, age, hometown)values('杨幂', '表演艺术',18,'湖北黄石') "
cur.execute(sqlstr6)
conn.commit()
print("Records created successfully")
conn.close()
展示数据:
import sqlite3
conn = sqlite3.connect("d:/test.db")
cur = conn.cursor()
sqlstr = "select * from user"
s = cur.execute(sqlstr)
for row in s:
print("name=",row[0])
print("profession=",row[1])
print("age=",row[2])
print("hometown=",row[3],'\n')
一些其他操作:更改、删除
import sqlite3
conn = sqlite3.connect("d:/test.db")
cur = conn.cursor()
sql_update = "update user set profession='多人运动' where name='罗志祥'"
#删除最好删主键 primary key
sql_update = "delete from user where name='王哲铭'"
cur.execute(sql_update)
conn.commit()
sql_select = "select * from user"
s = cur.execute(sql_select)
for row in s:
print("name=",row[0])
print("profession=",row[1])
print("age=",row[2])
print("hometown=",row[3],'\n')
二、Mysql
这真的是个巨烦人的地方,重装了成5.7结果以前项目的语法都错了,然后又再去装了5.5,但是网上好像搜每次只能启动一个版本数据库的服务,而且用过的孩子们也晓得net stop mysql
容易,再一次net start mysql
麻烦的脑壳疼。这里在网上看了些文章就做个分享windows安装两个mysql数据库 5.5 5.7 、docker安装多版本mysql、Linux下安装启动多个mysql 无奈中突然觉得有一丝想去入钻inux操作系统了emmm
略略略,就吐槽一下,我也是个小白哈
将你和5位同学的姓名、专业、年龄、籍贯数据保存成为mysql格式的数据库python之stu表中,并将这6条记录显示到屏幕上。
没写utf-8编码了,因为有些忘了emm,就索性英文编写了最简单的sql:
CREATE TABLE stu (
NAME VARCHAR(30) PRIMARY KEY,
profession VARCHAR(30),
age INT(8),
hometown VARCHAR(30)
);
INSERT INTO stu VALUES('wangzheming','Information Engineering',20,'ShiYanHuBei');
INSERT INTO stu VALUES('xiaozhan','Chinese Language Study',22,'WuHanHuBei');
INSERT INTO stu VALUES('caixukun','English translation',18,'EnShiHuBei');
INSERT INTO stu VALUES('wangyibo','Educational technology',25,'XianTaoHuBei');
INSERT INTO stu VALUES('luozhixiang','Beauty salons',16,'XiangYangHuBei');
INSERT INTO stu VALUES('yangmi','Performance art',20,'HuangShiHuBei');
python将这些显示到屏幕上:
import pymysql
# 打开数据库连接,此处需要自行配置,我用的Pycharm,在编辑器里有DataBase连接
db = pymysql.connect(host="localhost", user="root",
password="root", db="python", port=3306, charset='utf8')
# 使用cursor()方法获取操作游标
cur = db.cursor()
# 查询操作
# 编写sql 查询语句 stu 对应我的表名
sql = "select * from stu"
try:
cur.execute(sql) # 执行sql语句
results = cur.fetchall() # 获取查询的所有记录
print("name", "\tprofession", "\tage", "\thometown")
# 遍历结果
for row in results:
name = row[0]
profession = row[1]
age = row[2]
hometown = row[3]
print(name, profession, age, hometown, )
except Exception as e:
raise e
finally:
db.close() # 关闭连接
有些乱,勿喷、勿喷
模仿写了些插入、修改、查询、删除操作:
import pymysql
import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='python',
charset='utf8'
)
# 获取游标
cursor = connect.cursor()
# 插入数据
sql = "INSERT INTO stu (name, profession, age, hometown) VALUES ( '%s', '%s', %d, '%s' )"
data = ('lironghao', 'Music', 24, 'XianNingHuBei')
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')
# 修改数据
sql = "UPDATE stu SET age = %d WHERE name = '%s' "
data = (21, 'lironghao')
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '条数据')
# 查询数据
sql = "SELECT profession, hometown FROM stu WHERE name = '%s' "
data = ('xiaozhan',)
cursor.execute(sql % data)
for row in cursor.fetchall():
print("profession:%s\thometown:%s" % row)
print('共查找出', cursor.rowcount, '条数据')
# 删除数据
sql = "DELETE FROM stu WHERE name = '%s' LIMIT %d"
# 检索前 7 个记录行
data = ('lironghao', 7)
cursor.execute(sql % data)
connect.commit()
print('成功删除', cursor.rowcount, '条数据')
# 关闭连接
cursor.close()
connect.close()
附上一个符号表示意义表:
符号 | 意义 |
---|---|
%s | 字符串 |
%d | 十进制整数 |
%o | 八进制 |
%x | 十六进制整数 |
%f | 浮点数 |