python模块之MySQLdb: 用python连接mysql数据库
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/
有下载和文档。
由于python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的代码:
#
-*- encoding: gb2312 -*-
import
os, sys, string
import
MySQLdb
#
连接数据库
try
:
conn
=
MySQLdb.connect(host
=
'
localhost
'
,user
=
'
root
'
,passwd
=
'
xxxx
'
,db
=
'
test1
'
)
except
Exception, e:
print
e
sys.exit()
#
获取cursor对象来进行操作
cursor
=
conn.cursor()
#
创建表
sql
=
"
create table if not exists test1(name varchar(128) primary key, age int(4))
"
cursor.execute(sql)
#
插入数据
sql
=
"
insert into test1(name, age) values ('%s', %d)
"
%
(
"
zhaowei
"
,
23
)
try
:
cursor.execute(sql)
except
Exception, e:
print
e
sql
=
"
insert into test1(name, age) values ('%s', %d)
"
%
(
"
张三
"
,
21
)
try
:
cursor.execute(sql)
except
Exception, e:
print
e
#
插入多条
sql
=
"
insert into test1(name, age) values (%s, %s)
"
val
=
((
"
李四
"
,
24
), (
"
王五
"
,
25
), (
"
洪六
"
,
26
))
try
:
cursor.ex
相关文档:
复制记录,采用自查询方式
sql
INSERT INTO `table` ('id','aa','bb','cc') SELECT 'id','aa','bb','cc' from `table` (WHERE .....)
Tips:
/**
* 复制新纪录的时候,可能要更新id或者是部分数据(假设id自增加的情况)
*
* text_aa 为固定值 ,可在脚本调用中赋变量值 如($aa)
* 注意'text_aa' 与 `cc` 的区别 ......
MySQL分区(Partition)功能试验2008-07-06 20:02目录
[概述]
[分区表和未分区表试验过程]
[分区命令详解]
[概述]
自5.1开始对分区(Partition)有支持,6.0应比较稳定
= 水平分区(根据列属性按行分)=
举个简单例子:一个包含十年发票记录的表可以被分区为十个不同的分区,每个分区包含的是其中一年的记录。
=== 水 ......
一、MySQL 获得当前日期时间 函数
1.1 获得当前日期+时间(date + time)函数:now()
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2008-08-08 22:20:46 |
+---------------------+
除了 now() 函数能获得当前的日期时间外,MySQL 中还有下面的函数: ......
http://blog.163.com/mysqldba@126/blog/static/1315356342009931103834396/
最近看了看mysql的状态变量,感觉好多跟以前自己想象的不一样。为了以后能及时发现自己的错误,就先记下来;
http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html
mysql> show status;
Com_xxx
语句计数变量表示每个xxx ......
安装mysql
gem install mysql
使用mysql,如,rake db:migrate
会报错:
E:\study\ruby\rails_space>rake db:migrate
(in E:/study/ruby/rails_space)
!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
rake aborted!
193: ......