qder 发表于 2015-12-15 11:40:34

python操作数据库简单程序


[*]#!/usr/bin/python

[*]# coding=utf-8
[*]'''

[*]Created on 2015年4月13日
[*]Script : E:/EclipseCode/python/myTestDjango/src/myTestDjango/conn_db.py
[*]@author: ceagle
[*]'''
[*]import MySQLdb
[*]try:
[*]    #conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='myTestDjango',port=3306,charset='gbk')
[*]    conn=MySQLdb.connect(host='localhost',user='root',passwd='',port=3306,charset='gbk')
[*]    cur=conn.cursor()
[*]    cur.execute('create database if not exists myTestDjango')
[*]    conn.select_db('myTestDjango')
[*]   
[*]    #cur.execute('create table if not exists student (id int,name varchar(20))')
[*]    # insert single data
[*]    value = [1,'ceagle']
[*]    cur.execute('insert into student values (%s,%s)',value)
[*]    #insert many data
[*]    values = []
[*]    for i in range(5):
[*]      values.append((i,'student'+str(i)))
[*]    cur.executemany('insert into student values (%s,%s)',values)
[*]   
[*]   
[*]    #display
[*]    count = cur.execute('select * from student')
[*]    print 'There has %s lines in student' % count
[*]   
[*]    print '1 records:'
[*]    result = cur.fetchone()
[*]    print 'ID:%s Name:%s' % result
[*]    print "=="*10
[*]    print '3 records:'
[*]    result =cur.fetchmany(3)
[*]    for i in result:
[*]      print i
[*]    print "=="*10
[*]   
[*]    print 'all records:'
[*]    result =cur.fetchall()
[*]    for i in result:
[*]      print i
[*]    print "=="*10
[*]    #cur.execute('select * from mysql.user')
[*]    conn.commit()
[*]    cur.close()
[*]    conn.close()
[*]except MySQLdb.Error,e:
[*]    print "Mysql Error %d: %s" % (e.args[0], e.args[1])
页: [1]
查看完整版本: python操作数据库简单程序