python日记——数据库操作

来源:互联网 发布:华军软件下载中心 编辑:程序博客网 时间:2024/06/05 13:31

在说用pyhton实现之前先科普一下数据库常用的命令

1.终端启动MySQL:/etc/init.d/mysql start;(stop ,restart。)
 2.登录MySQL:mysql -uroot -p (用root账户登录),然后输入密码;
3.查看所有的数据库名字:show databases;
4.选择一个数据库操作: use database_name;
5.查看当前数据库下所有的表名:show tables;
6.创建一个数据库:create database database_name;
7.删除一个数据库:drop database database_name;
8.创建一个表: create table mytest( uid int(4) primary key auto_increment, uname varchar(20) not null);
9.删除一个表: drop table mytest;
10.SQL插入语句:insert into table_name(col1,col2) values(value1,value2);//datetime要用双引号引起来
11.SQL更新语句:update table_name set col1='value1',col2='value2' where where_definition;
12.SQL查询语句:select * from table_name where.......(最复杂的语句)//字符串类型要用单引号
13.SQL删除语句:delete from table_name where...
14.增加表结构的字段:alert table table_name add column field1 date ,add column field2 time...
15.删除表结构的字段:alert table table_name drop field1;
16.查看表的结构:show columns from table_name;
17.limit 的使用:select * from table_name limit 3;//每页只显示3行
select * from table_name limit 3,4 //从查询结果的第三个开始,显示四项结果。
此处可很好的用来作分页处理。
18.对查询结果进行排序: select * from table_name order by field1,orderby field2;多重排序
19.退出MySQL:exit;

接下来看pyhton代码

增:

import MySQLdbcon= MySQLdb.connect(host='localhost',user='root',passwd='root',db='dbname')cursor =con.cursor()sql ="insert into table_name(col1,col2) values(value1,value2)"cursor.execute(sql)con.commit()cursor.close()con.close()

删:

import MySQLdbcon= MySQLdb.connect(host='localhost',user='root',passwd='root',db='dbname')cursor =con.cursor()sql ="delete from table_name where col1=value1"cursor.execute(sql)con.commit()cursor.close()con.close()


查:

import MySQLdbcon= MySQLdb.connect(host='localhost',user='root',passwd='root',db='dbname')cursor =con.cursor()sql ="select * from table_name where col1=value1"#不加where和后面的东西就是查询表内的全部数据cursor.execute(sql)for row in cursor.fetchall():    print row#row是数组形式,对应每一个字段cursor.close()con.close()

改:

import MySQLdbcon= MySQLdb.connect(host='localhost',user='root',passwd='root',db='dbname')cursor =con.cursor()sql ="update table_name set col1='value1',col2='value2' where where_definition"cursor.execute(sql)con.commit()cursor.close()con.close()

#如果数据库语句中含变量要转化为字符串然后再和其他拼在一起#转化为字符串可用str(value1)sql ="insert into table_name(col1,col2) values("+value1+","+value2+")"

注意:增删改都要commit


其实python的数据库处理都是大同小异,只要明白语法就行了,如果是字符串的话别忘了要用引号哦。

0 0
原创粉丝点击