1. 数据库操作
数据库与文件系统类比
文件夹 数据库
文件(excel) 库(database)
sheet table
行 记录
列 属性项
数据库操作
show databases;
create database dbname;
use dbname;
drop database dbname;
数据表操作
show tables;
create table tbname (
attrname attrtype
);
attrype => int
varchar(n)
text
create table user2 (
id int primary key auto_increment,
username varchar(25),
password varchar(32),
age int
) engine=myisam default chaset=utf8;
desc tbname;
show create table tbname;
SQL语句操作
insert into tbname(column_name1, column_name2, .....) values(column_value1, column_value2, .....)
delete from tbname where col=value;
drop table tbname;
update tbname set column_name1=column_value1,column_name2=column_value2 where col=value;
select * from tbname;
select column_name1, column_name2,... from tbname;
select * from tbname where column_name1 = column_value1 and column_name2=column_value1;
select * from tbname where username like '%';
select count(*)...
select ip,url,code,count(*) group by ip,url,code;
order by asc(默认)/desc
limit
offset
md5()
2. MySQL操作数据库流程
导入库
创建连接
设置自动提交(可以省略)
执行sql
根据sql类型选择commit还是fetch
更改类型commit
查询类型fetchall/fetchone
关闭cursor, conn
import MySQLdb 导入mysql连接库
conn = MySQLdb.connect(host='localhost', port=3306, user='anzhihe', passwd='anzhihe', db='test', charset='utf8') 连接mysql数据库
cur = conn.cursor() 获取游标
conn.commit() 提交,innodb不会自动执行此条语句,需设置autocommit为True
conn.autocommit(True) 设置自动提交
cur.execute('') 执行SQL语句
cur.fetchone() 返回一条记录,元组
cur.fetchall() 返回所有记录
conn.rollback() 回滚
cur.close()
conn.close()