Python案例教学之Mysql数据库的数据导入与导出 -CSV文件【第九课】

319 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

1、将上述学生信息存入数据库中,表名为tb_score,读取该文件,用合适的数据类型存储文件内容,并打印输出所有内容。

在这里插入图片描述

1.首先创建数据库!

在这里插入图片描述

2.创建表

连接 StdDB数据库

config = {'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '1414141',
'db' : 'StDB'
}
conn = pymysql.connect(**config)

执行 SQL 创建 表tb_score

cursor = conn.cursor()
sql = "CREATE TABLE tb_score(ID INT NOT NULL, name VARCHAR(20) NULL,score INT NULL, PRIMARY KEY (ID))"
cursor.execute(sql)
conn.close()

将数据用多维列表方式存储在内存中

ls = []
ls.append([10001, "小明", 90])
ls.append([10002, "小白", 85])
ls.append([10003, "小兰", 83])
ls.append([10004, "小张", 92])
ls.append([10005, "小赵", 81])

多条数据插入数据库中

cursor = conn.cursor()
sql = "insert into tb_score(ID,name,score) values({0},'{1}',{2})"
try:
    for line in ls:
        cursor.execute(sql.format(*line))
    conn.commit()
except:
    conn.rollback()
finally:
    conn.close()

读取数据库中数据

cursor = conn.cursor()
sql = "select * from tb_score"
cursor.execute(sql)
rows = cursor.fetchall()
ls2 = list(map(list, rows))
conn.close()
print(ls2)

在这里插入图片描述

(1)插入一条学生记录信息:学号:10006,姓名:小花,成绩:92

插入一条数据

ls3 = [10006, "小花", 92]
cursor = conn.cursor()
sql = "insert into tb_score(ID,name,score) values({0},'{1}',{2})"
try:
    cursor.execute(sql.format(*ls3))
    conn.commit()
except:
    conn.rollback()
finally:
    conn.close()

在这里插入图片描述

(2)打印输出学生成绩在90分以下的所有学生信息

根据条件读取数据库的信息

cursor = conn.cursor()
sql = "select ID,name,score from tb_score where score<{0}"
cursor.execute(sql.format(90))
rows = cursor.fetchall()
rows = list(map(list, rows))
print(rows)

在这里插入图片描述

(3)删除小明的成绩

删除数据库中的数据

cursor = conn.cursor()
sql = " delete from tb_score where name=%s "
try:
    cursor.execute(sql, ["小明"])
    conn.commit()
except:
    conn.rollback()

在这里插入图片描述

实验题目:csv文件导入数据库

将StudentInfo.csv文件中的信息导入数据库StudentTest

import pymysql
# 连接 StudentTest数据库
config = {'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '1414141',
'db' : 'StudentTest''local_infile': 1
}
conn = pymysql.connect(**config)
 # 执行 SQL 创建 表tb_student
 cursor = conn.cursor()
 sql = "CREATE TABLE tb_student(ID INT NOT NULL, name VARCHAR(20) NULL,score INT NULL,final INT NULL, PRIMARY KEY (ID))"
 cursor.execute(sql)
 conn.close()
 # CSV数据高效导入 MYSQL
cursor = conn.cursor()
sql = " LOAD DATA LOCAL INFILE '{0}' INTO TABLE {1} CHARACTER SET GBK FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES "
try:
    cursor.execute(sql.format("D:/studentInfo.csv", "tb_student"))
    conn.commit()
except Exception as e:
    print(e)
    conn.rollback()
cursor = conn.cursor()
sql = "select * from tb_student"
cursor.execute(sql)
rows = cursor.fetchall()
ls2 = list(map(list, rows))
conn.close()
print(ls2)

在这里插入图片描述 在这里插入图片描述

数据库导出到csv文件

数据库StudentTest中的信息导出到csvdata.csv文件中

import pymysql
# 连接 StudentTest数据库
config = {'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '1414141',
'db' : 'StudentTest''local_infile': 1
}
conn = pymysql.connect(**config)
cursor = conn.cursor()
sql = " select * into outfile '{0}' CHARACTER SET GBK FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' from(select '学号','姓名 ','平均成绩','期末成绩' union select * from tb_student) as b  "
try:
    cursor.execute(sql.format("D:/csvdata.csv",))
    conn.commit()
except Exception as e:
    print(e)
    conn.rollback()
conn.close()

在这里插入图片描述 导出成功,查看CSV文件 在这里插入图片描述

出现‘The used command is not allowed with this MySQL version’错误

今天做实验时将csv数据导入数据库时出现‘The used command is not allowed with this MySQL version’错误,网上说是从本地导入文件的参数没有打开,在mysql.data升级之后,为了安全考虑,默认不允许加载本地文件数据。查找了好几个方法嫌麻烦,突然想起了老师原来讲过! 只需在连接数据库时添加local_infile:1就可以解决。

例如:

import pymysql
# 连接 StudentTest数据库
config = {'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '12346',
'db' : 'StudentTest'
}
conn = pymysql.connect(**config)

CSV数据导入会出错!

import pymysql
# 连接 StudentTest数据库
config = {'host': 'localhost',
'port': 3306,
'user': 'root',
'passwd': '12346',
'db' : 'StudentTest''local_infile': 1
}
conn = pymysql.connect(**config)

这样就不会出错了!