MySQL是Web世界中使用最普遍的数据库服务器,SQLite的特定是轻量级,可嵌入,但不能承受高并发访问,适合桌面和移动应用。而MySQL是为服务器端设计的数据库,能承受高并发访问,同时占用的内存也远远大于SQLite。此外,MySQL内部有多种数据库引擎,最经常使用的引擎是支持数据库事务的InnoDB。html
这里小编就不详细介绍了,要是有不会安装的能够参考下面博客python
http://www.cnblogs.com/wj-1314/p/7573242.htmlmysql
要想使python能够操做mysql 就须要MySQL-python驱动,它是python 操做mysql必不可少的模块。sql
下载地址:https://pypi.python.org/pypi/MySQL-python/数据库
下载MySQL-python-1.2.5.zip 文件以后直接解压。进入MySQL-python-1.2.5目录:服务器
>>python setup.py install并发
而后安装pymysql函数
pip install pymysql
测试很是简单,检查pymysql模块是否能够正常导入。(在操做数据库的时候,python2通常使用mysqldb,可是在python3中已经再也不支持mysqldb了,咱们能够用pymysql和mysql.connector。本文全部操做都是在python3的pymysql下完成的。)高并发
没有报错提示MySQLdb模块找不到,说明安装OK 测试
mysql> show databases; // 查看当前全部的数据库 +--------------------+ | Database | +--------------------+ | information_schema | | csvt | | csvt04 | | mysql | | performance_schema | | test | +--------------------+ rows in set (0.18 sec) mysql> use test; //做用与test数据库 Database changed mysql> show tables; //查看test库下面的表 Empty set (0.00 sec) //建立user表,name 和password 两个字段 mysql> CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); Query OK, 0 rows affected (0.27 sec) //向user表内插入若干条数据 mysql> insert into user values('Tom','1321'); Query OK, 1 row affected (0.05 sec) mysql> insert into user values('Alen','7875'); Query OK, 1 row affected (0.08 sec) mysql> insert into user values('Jack','7455'); Query OK, 1 row affected (0.04 sec) //查看user表的数据 mysql> select * from user; +------+----------+ | name | password | +------+----------+ | Tom | 1321 | | Alen | 7875 | | Jack | 7455 | +------+----------+ rows in set (0.01 sec) //删除name 等于Jack的数据 mysql> delete from user where name = 'Jack'; Query OK, 1 rows affected (0.06 sec) //修改name等于Alen 的password 为 1111 mysql> update user set password='1111' where name = 'Alen'; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 //查看表内容 mysql> select * from user; +--------+----------+ | name | password | +--------+----------+ | Tom | 1321 | | Alen | 1111 | +--------+----------+ rows in set (0.00 sec)
这里盗图一张,以流程图的方式展现python操做MySQL数据库的流程:
#coding=utf-8 import MySQLdb
# 打开数据库链接
conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', )
# 使用cursor()方法获取操做游标 cur = conn.cursor() #建立数据表 #cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") #插入一条数据 #cur.execute("insert into student values('2','Tom','3 year 2 class','9')") #修改查询条件的数据 #cur.execute("update student set class='3 year 1 class' where name = 'Tom'") #删除查询条件的数据 #cur.execute("delete from student where age='9'")
# 关闭游标 cur.close()
# 提交,否则没法保存新建或者修改的数据 conn.commit()
# 关闭数据库链接 conn.close()
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) conn.commit() cursor.close() conn.close() # 获取最新自增ID new_id = cursor.lastrowid
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.execute("select * from hosts") # 获取第一行数据 row_1 = cursor.fetchone() # 获取前n行数据 # row_2 = cursor.fetchmany(3) # 获取全部数据 # row_3 = cursor.fetchall() conn.commit() cursor.close() conn.close()
fetchone()方法能够帮助咱们得到表中的数据,但是每次执行cur.fetchone() 得到的数据都不同,换句话说我没执行一次,游标会从表中的第一条数据移动到下一条数据的位置,因此,我再次执行的时候获得的是第二条数据。fetchone()函数的返回值是单个的元组,也就是一行记录,若是没有,就返回null
fetchall() 函数的返回值是多个元组,即返回多个行记录,若是没有,返回的是()、
注:在fetch数据时按照顺序进行,可使用cursor.scroll(num,mode)来移动游标位置,如:
关于默认获取的数据是元祖类型,若是想要或者字典类型的数据,即:
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') # 游标设置为字典类型 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) r = cursor.execute("call p1()") result = cursor.fetchone() conn.commit() cursor.close() conn.close()
经过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:
>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
我要想插入新的数据,必需要对这条语句中的值作修改。咱们能够作以下修改:
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #插入一条数据 sqli="insert into student values(%s,%s,%s,%s)" cur.execute(sqli,('3','Huhu','2 year 1 class','7')) cur.close() conn.commit() conn.close()
假如要一次向数据表中插入多条值呢?
executemany()方法能够一次插入多条值,执行单挑sql语句,可是重复执行参数列表里的参数,返回值为受影响的行数。
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #一次插入多条记录 sqli="insert into student values(%s,%s,%s,%s)" cur.executemany(sqli,[ ('3','Tom','1 year 1 class','6'), ('3','Jack','2 year 1 class','7'), ('3','Yaheng','2 year 2 class','7'), ]) cur.close() conn.commit() conn.close()
#!/usr/bin/env python # coding=utf-8 import pymysql def connectdb(): print('链接到mysql服务器...') # 打开数据库链接 # 用户名:hp, 密码:Hp12345.,用户名和密码须要改为你本身的mysql用户名和密码,而且要建立数据库TESTDB,并在TESTDB数据库中建立好表Student db = pymysql.connect("localhost","hp","Hp12345.","TESTDB") print('链接上了!') return db def createtable(db): # 使用cursor()方法获取操做游标 cursor = db.cursor() # 若是存在表Sutdent先删除 cursor.execute("DROP TABLE IF EXISTS Student") sql = """CREATE TABLE Student ( ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )""" # 建立Sutdent表 cursor.execute(sql) def insertdb(db): # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 插入语句 sql = """INSERT INTO Student VALUES ('001', 'CZQ', 70), ('002', 'LHQ', 80), ('003', 'MQ', 90), ('004', 'WH', 80), ('005', 'HP', 70), ('006', 'YF', 66), ('007', 'TEST', 100)""" #sql = "INSERT INTO Student(ID, Name, Grade) \ # VALUES ('%s', '%s', '%d')" % \ # ('001', 'HP', 60) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # Rollback in case there is any error print '插入数据失败!' db.rollback() def querydb(db): # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 查询语句 #sql = "SELECT * FROM Student \ # WHERE Grade > '%d'" % (80) sql = "SELECT * FROM Student" try: # 执行SQL语句 cursor.execute(sql) # 获取全部记录列表 results = cursor.fetchall() for row in results: ID = row[0] Name = row[1] Grade = row[2] # 打印结果 print "ID: %s, Name: %s, Grade: %d" % \ (ID, Name, Grade) except: print "Error: unable to fecth data" def deletedb(db): # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 删除语句 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100) try: # 执行SQL语句 cursor.execute(sql) # 提交修改 db.commit() except: print '删除数据失败!' # 发生错误时回滚 db.rollback() def updatedb(db): # 使用cursor()方法获取操做游标 cursor = db.cursor() # SQL 更新语句 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003') try: # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: print '更新数据失败!' # 发生错误时回滚 db.rollback() def closedb(db): db.close() def main(): db = connectdb() # 链接MySQL数据库 createtable(db) # 建立表 insertdb(db) # 插入数据 print '\n插入数据后:' querydb(db) deletedb(db) # 删除数据 print '\n删除数据后:' querydb(db) updatedb(db) # 更新数据 print '\n更新数据后:' querydb(db) closedb(db) # 关闭数据库 if __name__ == '__main__': main()
练习题:
参考表结构:
用户类型
用户信息
权限
用户类型&权限
功能:
# 登录、注册、找回密码
# 用户管理
# 用户类型
# 权限管理
# 分配权限
特别的:程序仅一个可执行文件
SQLite是一种嵌入式数据库,它的数据库就是一个文件。因为SQLite自己是C写的,并且体积很小。因此,常常被集成到各类应用程序中,甚至在iOS 和 Android 的APP中均可以集成。
Python就内置了SQLite3,因此在python中使用SQLite,不须要安装任何东西,直接使用。
在使用SQLite以前,咱们先要搞清楚几个概念:
表是数据库中存放关系数据的集合,一个数据库里面一般都包含多个表,好比学生的表,班级的表,学校的表等等。表和表之间经过外键关联。
要操做关系数据库,首先须要链接到数据库,一个数据库链接成为Connection;
链接到数据库后,须要打开游标,称之为Cursor,经过Cursor执行SQL语句,而后得到执行结果。
Python定义了一套操做数据库的API接口,任何数据库要链接到Python,只须要提供符合Python标准的数据库驱动便可。
因为SQLite的驱动内置在Python标准库中,因此咱们能够直接来操做SQLite数据库。
咱们在Python交互式命令行实践一下:
# 导入SQLite驱动: >>> import sqlite3 # 链接到SQLite数据库 # 数据库文件是test.db # 若是文件不存在,会自动在当前目录建立: >>> conn = sqlite3.connect('test.db') # 建立一个Cursor: >>> cursor = conn.cursor() # 执行一条SQL语句,建立user表: >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') <sqlite3.Cursor object at 0x10f8aa260> # 继续执行一条SQL语句,插入一条记录: >>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')') <sqlite3.Cursor object at 0x10f8aa260> # 经过rowcount得到插入的行数: >>> cursor.rowcount 1 # 关闭Cursor: >>> cursor.close() # 提交事务: >>> conn.commit() # 关闭Connection: >>> conn.close()
咱们再试试查询记录:
>>> conn = sqlite3.connect('test.db') >>> cursor = conn.cursor() # 执行查询语句: >>> cursor.execute('select * from user where id=?', ('1',)) <sqlite3.Cursor object at 0x10f8aa340> # 得到查询结果集: >>> values = cursor.fetchall() >>> values [('1', 'Michael')] >>> cursor.close() >>> conn.close()
使用Python的DB-API时,只要搞清楚connection 和cursor对象,打开后必定记得关闭,就能够放心使用。
使用cursor对象执行insert,update,delete语句时,执行结果由rowcount返回影响的行数,就能够拿到执行结果。
使用cursor对象执行select语句时,经过featchall() 能够拿到结果集,结果集是一个list,每一个元素都是一个tuple,对应一行记录。
若是SQL语句带有参数,那么须要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:
ursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))
练习:
import os, sqlite3 db_file = os.path.join(os.path.dirname(__file__), 'test.db') print(db_file) # E:/backup/pycode/now/ProcessDataPreprocessing/code\test.db if os.path.isfile(db_file): os.remove(db_file) # 初始化数据 conn = sqlite3.connect(db_file) cursor = conn.cursor() sql1 = 'create table user(id varchar(20) primary key , name varchar(20), score int)' cursor.execute(sql1) sql2 = "insert into user values ('001','james', 99)" cursor.execute(sql2) sql3 = "insert into user values ('002','durant', 99)" cursor.execute(sql3) cursor.close() conn.commit() conn.close()
查询操做:
# 查询记录: conn = sqlite3.connect('test.db') cursor = conn.cursor() # 执行查询语句: sql4 = 'select * from user ' cursor.execute(sql4) # 得到查询结果集: values = cursor.fetchall() print(values) cursor.close() conn.close()
参考文献:https://www.2cto.com/database/201807/761697.html