MySQL数据库以及其Python用法
一 命令行模式下:
mysql -u root -p # 进入进入mysql命令行模式 show databases; # 查看所有数据库 create database data; # 创建数据库,名为data use blog; # blog 是一个数据库名 show tables; create table persons( personid int, name varchar(255) ); # 在数据库下创建表persons. show columns from post; # post是数据库blog中一张表名。 select * from post; select (distinct) title,content from post; # 加distinct后可以去重 select timestamp from post where title='文章标题'; # where为条件语句 SELECT * FROM Websites WHERE alexa > 15 AND (country='CN' OR country='USA'); # and,or对条件过滤 select title from post order by timestamp (desc); # order by 以timestamp排序,默认升序,如要降序加上desc insert into post(title,content,timestamp) values ('title','content','20171207'); # 往post表中插入值 update post set content='google.com' where title='title'; # 更新已存在的字段 delete from post (where title='title'); # 删除表(表中行) truncate table post; # 只删除表中内容,不删除表结构。 drop table persons; # 删除表 drop database data; # 删除数据库
二 用Python连接MySQL及使用
import pymysql # 连接mysql conn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8',cursorclass = pymysql.cursors.DictCursor) # mysql数据库默认查到结果是tuple类型,加入cursorclass 目的是让结果为list类型。 conn.autocommit(True) cursor = conn.cursor() # 操作mysql query = ('select id, name from my_school') cursor.execute(query) # 查询 (不论是什么数据类型,占位符都用%s) query = ('select id, name from my_school where id > %s and id < %s') cursor.execute(query, (7, 12)) # 插入 cursor.execute('insert into post(title,content,timestamp) values (%s,%s,%s)', ('title','content','20171207170844')) # 后面填入的数据是格式可以是list[],也可以是tuple() # 更新 cursor.execute('update post set title=%s,content=%s where id=%s', ('图书馆','图书馆真是个学习和看书的好地方','3')) # set后面连续的条件不能用括号括起来,直接逗号隔开即可。 # 删除 cursor.execute("delete from post where title='title'") # 获取数据 cursor.fetchone() cursor.fetchall() # 关闭mysql连接 cursor.close() conn.close()