主页

索引

模块索引

搜索页面

2.6.5. mysql-python

  • 安装:

    easy_install mysql-python
    
  • 使用:

    import MySQLdb # 注意大小写
    
  • 创建数据库,创建表,插入数据,插入多条数据

 1#!/usr/bin/env python
 2#coding=utf-8
 3
 4##################################
 5#MySQLdb 示例
 6##################################
 7import MySQLdb
 8
 9#建立和数据库系统的连接
10conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
11
12#获取操作游标
13cursor = conn.cursor()
14#执行SQL,创建一个数据库.
15cursor.execute("""create database if not exists python""")
16
17#选择数据库
18conn.select_db('python');
19#执行SQL,创建一个数据表.
20cursor.execute("""create table test(id int, info varchar(100)) """)
21
22value = [1,"inserted ?"];
23
24#插入一条记录
25cursor.execute("insert into test values(%s,%s)",value);
26
27values=[]
28
29
30#生成插入参数值
31for i in range(20):
32    values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
33#插入多条记录
34
35cursor.executemany("""insert into test values(%s,%s) """,values);
36
37#关闭连接,释放资源
38cursor.close();
  • 实例二:

 1#!/usr/bin/env python
 2#coding=utf-8
 3######################################
 4#
 5# MySQLdb 查询
 6#
 7#######################################
 8
 9import MySQLdb
10
11conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')
12
13cursor = conn.cursor()
14
15count = cursor.execute('select * from test')
16
17print '总共有 %s 条记录',count
18
19#获取一条记录,每条记录做为一个元组返回
20print "只获取一条记录:"
21result = cursor.fetchone();
22print result
23#print 'ID: %s   info: %s' % (result[0],result[1])
24print 'ID: %s   info: %s' % result 
25
26#获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录
27print "只获取5条记录:"
28results = cursor.fetchmany(5)
29for r in results:
30    print r
31
32print "获取所有结果:"
33#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,
34cursor.scroll(0,mode='absolute')
35#获取所有结果
36results = cursor.fetchall()
37for r in results:
38    print r
39conn.close()

主页

索引

模块索引

搜索页面