python使用MySQLdb访问mysql数据库的方法

yipeiwu_com6年前Python基础

本文实例讲述了python使用MySQLdb访问mysql数据库的方法。分享给大家供大家参考。具体如下:

#!/usr/bin/python
import MySQLdb
def doInsert(cursor,db):
 #insert
 # Prepare SQL query to INSERT a record into the database.
 sql = "UPDATE EMPLOYEE SET AGE = AGE+1 WHERE SEX = '%c'" %('M')
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
def do_query(cursor,db):
 sql = "SELECT * FROM EMPLOYEE \
     WHERE INCOME > '%d'" % (1000)
 try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   print 'resuts',cursor.rowcount
   for row in results:
    fname = row[0]
    lname = row[1]
    age = row[2]
    sex = row[3]
    income = row[4]
    # Now print fetched result
    print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
        (fname, lname, age, sex, income )
 except:
   print "Error: unable to fecth data"
def do_delete(cursor,db):
 sql = 'DELETE FROM EMPLOYEE WHERE AGE > {}'.format(20)
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
def do_insert(cursor,db,firstname,lastname,age,sex,income):
 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
    LAST_NAME, AGE, SEX, INCOME) \
    VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
    (firstname,lastname,age,sex,income)
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
# Open database connection
# change this to your mysql account
#connect(server,username,password,db_name)
db = MySQLdb.connect("localhost","hunter","hunter","pydb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
do_query(cursor,db)
doInsert(cursor,db)
do_query(cursor,db)
do_delete(cursor,db)
do_query(cursor,db)
do_insert(cursor,db,'hunter','xue',22,'M',2000)
do_insert(cursor,db,'mary','yang',22,'f',5555)
do_insert(cursor,db,'zhang','xue',32,'M',5000)
do_insert(cursor,db,'hunter','xue',22,'M',333)
do_query(cursor,db)
# disconnect from server
db.close()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python常见文件操作的函数示例代码

复制代码 代码如下: # -*-coding:utf8 -*- ''' Python常见文件操作示例 os.path 模块中的路径名访问函数 分隔 basename() 去掉目录路径,...

python版DDOS攻击脚本

本文实例为大家分享了python版DDOS攻击脚本,供大家参考,具体内容如下 于是就找到了我之前收藏的一篇python的文章,是关于ddos攻击的一个脚本,正好今天有空,就实践下了。 附...

跟老齐学Python之总结参数的传递

就前面所讲,函数的基本内容已经完毕。但是,函数还有很多值得不断玩味的细节。这里进行阐述。 参数的传递 python中函数的参数通过赋值的方式来传递引用对象。下面总结通过总结常见的函数参数...

详解TensorFlow查看ckpt中变量的几种方法

查看TensorFlow中checkpoint内变量的几种方法 查看ckpt中变量的方法有三种: 在有model的情况下,使用tf.train.Saver进行restore...

python socket多线程通讯实例分析(聊天室)

本文实例讲述了python socket多线程通讯方法。分享给大家供大家参考,具体如下: #!/usr/bin/evn python """ 这是一个Socket+多进程的例子(聊天...