[python]-mysqldb 使用方法

本文提供了使用 Python 的 MySQLdb 库进行数据库操作的示例代码,包括数据库和表的创建、数据的插入及查询等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章转自:http://blog.youkuaiyun.com/wanghai__/article/details/6718297

略去MySQLdb的安装,使用django的时候已经安装完毕。


#!/usr/bin/env python  
#coding=utf-8  
import MySQLdb  
 
#建立和数据库系统的连接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
 
#获取操作游标  
cursor = conn.cursor()  
#执行SQL,创建一个数据库.  
cursor.execute("""create database python """)  
 
#关闭连接,释放资源  
cursor.close();  

#!/usr/bin/env python  
#coding=utf-8  
import MySQLdb  
 
#建立和数据库系统的连接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
 
#获取操作游标  
cursor = conn.cursor()  
#执行SQL,创建一个数据库.  
cursor.execute("""create database if not exists python""")  
 
#选择数据库  
conn.select_db('python');  
#执行SQL,创建一个数据表.  
cursor.execute("""create table test(id int, info varchar(100)) """)  
 
value = [1,"inserted ?"];  
#插入一条记录  
cursor.execute("insert into test values(%s,%s)",value);  
 
values=[]  
#生成插入参数值  
for i in range(20):  
    values.append((i,'Hello mysqldb, I am recoder ' + str(i)))  
#插入多条记录  
cursor.executemany("""insert into test values(%s,%s) """,values);  
 
#关闭连接,释放资源  
cursor.close();  

#!/usr/bin/env python  
#coding=utf-8  
 
import MySQLdb  
 
conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')  
cursor = conn.cursor()  
count = cursor.execute('select * from test')  
print '总共有 %s 条记录',count  
 
#获取一条记录,每条记录做为一个元组返回  
print "只获取一条记录:" 
result = cursor.fetchone();  
print result  
#print 'ID: %s   info: %s' % (result[0],result[1])  
print 'ID: %s   info: %s' % result   
 
#获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录  
print "只获取5条记录:" 
results = cursor.fetchmany(5)  
for r in results:  
    print r  
 
print "获取所有结果:" 
#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,  
cursor.scroll(0,mode='absolute')  
#获取所有结果  
results = cursor.fetchall()  
for r in results:  
    print r  
conn.close()  


pyodbc在windows下的安装:

1、Download ez_setup. http://peak.telecommunity.com/dist/ez_setup.py

2、Create c:\python\scripts\ and place ez_setup.py

3、Run ez_setup.py (you may need to explicitly call python like c:\python\python.exe ez_setup.py). This will make it easier to install python eggs.

4、Normally you can type in easy_install pyodbc and it will search for eggs (easy_install.exe pyodbc)

5、test, import pyodbc

http://www.sperris.com/todays_goal/2008/10/installing-pyodbc-on-windows.html





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值