python 中使用sqlite3和mysql数据库

来源:互联网 发布:linux telnet ip 端口 编辑:程序博客网 时间:2024/05/16 14:52
sqlite是小型嵌入式数据库,支持大部分sql语句

sqlite3支持的时间数据类型:
date      包含了年份、月份、日期
time      包含了小时、分钟、秒
timestamp 包含了年、月、日、时、分、秒、毫秒

时间函数:
datetime() : 产生日期和时间
date(): 产生日期
time():产生时间
strftime():对以上3个函数产生的日期和时间进行格式化

e.g: date('2011-9-9','+1 day','+1 year'); 结果是 2010-09-10

数据库的连接对象常用函数:
commit()--事务提交
rollback()--事务回滚
close()--关闭一个数据库连接
cursor()--创建一个游标

游标对象常用函数:
execute()--执行sql语句
executemany()--执行多条sql语句
close()--关闭游标
fetchone()--从结果中取一条记录
fetchmany()--从结果中取多条记录
fetchall()--从结果中取出多条记录
scroll()--游标滚动

import MySQLdb
import sqlite3
mysqlConn = MySQLdb.connect(host='',user='',passwd='',db='', port= , charset='')

sqliteConn = sqlite3.connect('xx.db') ,没有就创建数据库,
在sqlite每一个数据库中,都有一张表sqlite_master,它定义数据库的模式,对于表来说,type 字段永远是 ‘table’,name 字段永远是表的名字。所以,要获得数据库中所有表的列表,可以:
cur.execute('select name from sqlite_master where type="table"')
第一次创建表:
tablename = cur.fetchone()
if tablename == None:
   cur.execute('create table admin(DATE timestamp PRIMARY KEY,username text ,age integer')
   sqliteConn.commit()
cur.close()

插入数据:  insert into 表名(字段列表) values(值列表) e.g: insert  into admin values('2014-03-24',‘song’,25);
查询数据:  select 字段名 from 表名 where 条件语句     e.g: select DATE from admin order by DATE desc;
删除数据:  delete from 表名 where 条件子句           e.g: cur.execute('delete from admin where DATE = "%s"' %date)  注意"%s",要加引号
修改数据:  update 表名 set 字段名=值 where 条件子句   e.g:update admin set username=’zhang’,age=24 where username=’song’ and age=25;

in() 查询:cur.execute("select bug_id,assigned_to from bugs where product_id =%s AND assigned_to in (%s)" %(productid, assigned_toStr))

select max(datatime) from   where   ;
select min(datatime) from   where   ;
coalesce()解释:返回参数中的第一个非空表达式(从左向右);

不等于 <>


模糊查询like
SELECT 字段 FROM 表 WHERE 某字段 LIKE 条件
(1)%:表示任意0个或多个字符
(2)_:表示任意单个字符,匹配单个任意字符,常用来限制表达式的字符长度语句。
(3)[ ]:表示括号内所列字符中的一个(类似正则表达式)
   select * from admin where username like ‘[张李王]三’;  表示搜索的是“张三”,“李三”或“王三”
(4)[^]表示不在括号所列之类的单个字符。
(5)查询内容包含通配符时,用“[ ]”括起来。

cur = mysqlConn.cursor()  定义了一个游标
遍历cur的2中方法:
while True:
    res = cur.fetchone()
    if res:
        print res
    else:
        break

res = cur.fetchall()
for i in range(len(res)):
    pirnt i




0 0
原创粉丝点击