大家好,我是Python进阶者。
我们在进行Python编程的时候,时常要将一些数据保存起来,其中最方便的莫过于保存在文本文件了。但是如果保存的文件太大,用文本文件就不太现实了,毕竟打开都是个问题,这个时候我们需要用到数据库。提到数据库,相信大部分人都不会陌生,今天我们要学的就是数据库中小编自认为最棒的Mysql数据库了。
为了让Python与Mysql 交互,这里我们需要用到Pymsql模块才行。
下载模块:
复制
pip install pymysql
1.
导入模块:
复制
import pymysql
1.
打开数据库连接软件 SqlYong,如图:
输入命令:
复制
CREATE DATABASE IF NOT EXISTS people;
1.
这样就创建了一个people 数据库。
复制
USE people; CREATE TABLE IF NOT EXISTS student(id INT PRIMARY KEY AUTO_INCREMENT,NAME CHAR(10) UNIQUE,score INT NOT NULL,tim DATETIME)ENGINE=INNOBASE CHARSET utf8; INSERT INTO student(NAME,score,tim)VALUES('fasd',60,'2020-06-01') SELECT * FROM student;
1.
2.
3.
4.
通过上述操作便创建了一个数据表Student并向其中写入了数据,结果如下:
我们可以一行代码删除这个插入的 数据:
复制
TRUNCATE student;
1.
将下图中的参数依次填入初始化参数中,
复制
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
1.
这样就连接到了people数据库,可以看下连接成功的打印信息:
可以看到我们打印了Mysql的版本和Host信息。
1.创建游标
复制
cur=db.cursor
1.
2.编写插入数据表达式
复制
sql="INSERT INTO student(NAME,score,tim)VALUES('任性的90后boy',100,now())"
1.
3.开启游标事件
复制
cur.begin()
1.
4.执行数据库语句,异常判断
复制
try: cur.execute(sql) 执行数据库语句 except Exception as e: print(e) db.rollback() 发生异常进行游标回滚操作 else: db.commit() 提交数据库操作 finally: cur.close() 关闭游标 db.close() 关闭数据库
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
5.执行插入操作
数据库建立好后,我们可以对它们进行插入数据的操作。
复制
import time db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() sql="INSERT INTO student(NAME,score,tim) VALUES ('%s',%d,'%s')" data=('HW',90,tt) try: cur.execute(sql%data) except Exception as e: print(e) db.rollback() else: db.commit() finally: cur.close() db.close()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
这样就可以将数据插入进去了。我们还可以自定义插入:
复制
import pymysql import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() s=input('string:') d=input('number:') sql="INSERT INTO student(NAME,score,tim)VALUES('%s','%s','%s')" try: data=(s,d,tt) cur.execute(sql%data) except Exception as e: print(e) db.rollback() else: db.commit() finally: cur.close() db.close()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
另外,我们也可以同时插入多条数据,只需先定义好所有的数据,然后在调用即可,这里需要用到插入多条数据的函数Executemany,在这里我插入十万条数据,并测试插入时间,步骤如下:
复制
import pymysql import time start=time.time() tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() sql="insert into student(NAME,score,tim)values(%s,%s,%s)" def get(): ab=[] for y in range(1,100000): if y>=100: data=('user-'+str(y),str(str(float('%.f'%(y%100)))),tt) else: data=('user-'+str(y),str(y),tt) ab.append(data) return ab try: data=get() cur.executemany(sql,data) except Exception as e: print(e) db.rollback() else: db.commit() finally: print('插入数据完毕') cur.close() db.close() end=time.time() print('用时:',str(end-start))
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
6.执行更新操作
有些数据我们觉得它过时了,想更改,就要更新它的数据。
复制
import time db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() sql="update student set name='zjj' where score=100 " 当分数是100分的时候将名字改为zjj try: cur.execute(sql%data) except Exception as e: print(e) db.rollback() else: db.commit() finally: cur.close() db.close()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
7.执行删除操作
有时候一些数据如果对于我们来说没有任何作用了的话了,我们就可以将它删除了,不过这里是删除数据表中的一条记录。
复制
import pymysql db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() sql="delete from student where name='fasd';" 当名字等于‘fasd’的时候删除这个记录 try: cur.execute(sql) except Exception as e: print(e) db.rollback() else: db.commit() finally: cur.close() db.close()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
你也可以删除表中所有的数据,只需将Sql语句改为:
复制
sql='TRUNCATE student;'
1.
当然你也可以删除表,但是一般不建议这样做,以免误删:
复制
DROP TABLE IF EXISTS student;
1.
8.执行查询操作
有时候我们需要对数据库中的数据进行查询,Python也能轻松帮我们搞定。
复制
import pymysql import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people') cur=db.cursor() db.begin() sql="select * from student;" try: cur.execute(sql) res=cur.fetchall() 查询数据库中的数据 for y in res: print(y) 打印数据库中标的所有数据,以元祖的形式 except Exception as e: print(e) db.rollback() else: db.commit() finally: cur.close() db.close()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
在我们进行网络爬虫的时候,需要保存大量数据,这个时候数据库就派上用场了,可以更方便而且更快捷保存数据。