Python编程也能操作Mysql数据库,怎么弄?
Python编程的时候,时常要将一些数据保存起来,其中最方便的莫过于保存在文本文件了。但是如果保存的文件太大,用文本文件就不太现实了,毕竟打开都是个问题,这个时候我们需要用到数据库。提到数据库,相信大部分人都不会陌生,今天我们要学的就是数据库中小编自认为最棒的Mysql数据库了。
一、下载导入模块
为了让Python与Mysql 交互,这里我们需要用到Pymsql模块才行。
下载模块:
pip install pymysql
导入模块:
import pymysql
二、创建数据库
打开数据库连接软件 SqlYong,如图:

输入命令:
CREATE DATABASE IF NOT EXISTS people;
这样就创建了一个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;
通过上述操作便创建了一个数据表Student并向其中写入了数据,结果如下:

我们可以一行代码删除这个插入的 数据:
TRUNCATE student;
四、Mysql与Python建立连接
将下图中的参数依次填入初始化参数中,

db=(host='localhost',user='root',password='123456',port=3306,db='people')
这样就连接到了people数据库,可以看下连接成功的打印信息:

可以看到我们打印了Mysql的版本和Host信息。
五、创建游标执行操作
1.创建游标
cur=
2.编写插入数据表达式
sql="INSERT INTO student(NAME,score,tim)VALUES('任性的90后boy',100,now())"
3.开启游标事件
cur.begin()
4.执行数据库语句,异常判断
try:(sql) 执行数据库语句except Exception as e:print(e)() 发生异常进行游标回滚操作else:() 提交数据库操作finally:() 关闭游标() 关闭数据库
5,执行插入操作
数据库建立好后,我们可以对它们进行插入数据的操作。
import timedb=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()sql="INSERT INTO student(NAME,score,tim) VALUES ('%s',%d,'%s')"data=('HW',90,tt)try:(sql%data)except Exception as e:print(e)()else:()finally:()()

这样就可以将数据插入进去了。我们还可以自定义插入:
import pymysqlimport timett=('%Y-%m-%d %H:%M:%S',(()))db=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()s=input('string:')d=input('number:')sql="INSERT INTO student(NAME,score,tim)VALUES('%s','%s','%s')"try:data=(s,d,tt)(sql%data)except Exception as e:print(e)()else:()finally:()()

另外,我们也可以同时插入多条数据,只需先定义好所有的数据,然后在调用即可,这里需要用到插入多条数据的函数Executemany,在这里我插入十万条数据,并测试插入时间,步骤如下:
import pymysqlimport timestart=()tt=('%Y-%m-%d %H:%M:%S',(()))db=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()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)(data)return abtry:data=get()many(sql,data)except Exception as e:print(e)()else:()finally:print('插入数据完毕')()()end=()print('用时:',str(end-start))
6.执行更新操作
有些数据我们觉得它过时了,想更改,就要更新它的数据。
import timedb=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()sql="update student set name='zjj' where score=100 " 当分数是100分的时候将名字改为zjjtry:(sql%data)except Exception as e:print(e)()else:()finally:()()

7.执行删除操作
有时候一些数据如果对于我们来说没有任何作用了的话了,我们就可以将它删除了,不过这里是删除数据表中的一条记录。
import pymysqldb=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()sql="delete from student where name='fasd';" 当名字等于‘fasd’的时候删除这个记录try:(sql)except Exception as e:print(e)()else:()finally:()()

你也可以删除表中所有的数据,只需将Sql语句改为:
sql='TRUNCATE student;'
当然你也可以删除表,但是一般不建议这样做,以免误删:
DROP TABLE IF EXISTS student;
8.执行查询操作
有时候我们需要对数据库中的数据进行查询,Python也能轻松帮我们搞定。
import pymysqlimport timett=('%Y-%m-%d %H:%M:%S',(()))db=(host='localhost',user='root',password='123456',port=3306,db='people')cur=()()sql="select * from student;"try:(sql)res=() 查询数据库中的数据for y in res:print(y) 打印数据库中标的所有数据,以元祖的形式except Exception as e:print(e)()else:()finally:()()
六、总结
在我们进行网络爬虫的时候,需要保存大量数据,这个时候数据库就派上用场了,可以更方便而且更快捷保存数据。
THE END






