点击(此处)折叠或打开

  1. #!/usr/bin/python
  2. # coding=utf-8
  3. '''
  4. Created on 2015年4月13日
  5. Script : E:/EclipseCode/python/myTestDjango/src/myTestDjango/conn_db.py
  6. @author: ceagle
  7. '''
  8. import MySQLdb
  9. try:
  10.     #conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='myTestDjango',port=3306,charset='gbk')
  11.     conn=MySQLdb.connect(host='localhost',user='root',passwd='',port=3306,charset='gbk')
  12.     cur=conn.cursor()
  13.     cur.execute('create database if not exists myTestDjango')
  14.     conn.select_db('myTestDjango')
  15.     
  16.     #cur.execute('create table if not exists student (id int,name varchar(20))')
  17.     # insert single data
  18.     value = [1,'ceagle']
  19.     cur.execute('insert into student values (%s,%s)',value)
  20.     #insert many data
  21.     values = []
  22.     for i in range(5):
  23.         values.append((i,'student'+str(i)))
  24.     cur.executemany('insert into student values (%s,%s)',values)
  25.     
  26.     
  27.     #display
  28.     count = cur.execute('select * from student')
  29.     print 'There has %s lines in student' % count
  30.     
  31.     print '1 records:'
  32.     result = cur.fetchone()
  33.     print 'ID:%s Name:%s' % result
  34.     print "=="*10
  35.     print '3 records:'
  36.     result =cur.fetchmany(3)
  37.     for i in result:
  38.         print i
  39.     print "=="*10
  40.     
  41.     print 'all records:'
  42.     result =cur.fetchall()
  43.     for i in result:
  44.         print i
  45.     print "=="*10
  46.     #cur.execute('select * from mysql.user')
  47.     conn.commit()
  48.     cur.close()
  49.     conn.close()
  50. except MySQLdb.Error,e:
  51.     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

09-25 15:58