Python操作MySQL

来源:互联网 发布:神途相比传奇优化在哪 编辑:程序博客网 时间:2024/06/01 21:00

1、如果操作系统是ubuntu,则直接sudo apt-get install python-mysqldb,安装完成之后可以在python解释器中测试一下,输入python如下代码:import MySQLdb,如果不报错,则证明安装成功。


2、用python建立数据库

import MySQLdb  try:# 建立和数据库系统的连接  conn = MySQLdb.connect(host='localhost', user='root', passwd='root', port=3306)  # 获取操作游标  cursor = conn.cursor()  # 执行SQL,创建一个数据库 cursor.execute('create database python')      # 关闭连接,释放资源      cursor.close()conn.close()except MySQLdb.Error, e:        print 'Mysql Error %d: %s' % (e.args[0], e.args[1])


3、创建表,插入更新一条数据,插入多条数据

import MySQLdb  try:# 建立和数据库系统的连接  conn = MySQLdb.connect(host='localhost', user='root', passwd='root', port=3306)  # 获取操作游标  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, 'hi python']# 插入一条记录  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.execute('update test set info='Hello mysqldb, I am pythoner' where id=3')    # 提交事务    conn.commit()    # 关闭连接,释放资源      cursor.close()    conn.close()except MySQLdb.Error, e:        print 'Mysql Error %d: %s' % (e.args[0], e.args[1])

4、查询数据,删除数据

import MySQLdb  try:conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='python', port=3306)  cursor = conn.cursor()  count = cursor.execute('select * from test')  print '总共有%s条记录' % count    # 获取一条记录,每条记录做为一个元组返回  print '只获取一条记录:'  result = cursor.fetchone()print result    print 'ID: %s info: %s' % result     # 获取五条记录,注意由于之前执行了fetchone(),所以游标已经指到第二条记录,即从第二条开始的所有记录  print '只获取五条记录:'  results = cursor.fetchmany(5)  for r in results:      print r  # 删除一条记录cursor.execute('delete from test where id=0')print '获取所有结果:'  # 重置游标位置,0为偏移量,mode=absolute | relative,默认为relative  cursor.scroll(0, mode='absolute')  # 获取所有结果  results = cursor.fetchall()  for r in results:      print r  conn.commit()cursor.close()conn.close() except MySQLdb.Error, e:     print 'Mysql Error %d: %s' % (e.args[0], e.args[1])

说明:

charset属性根据需要自行指定,否则中文出现乱码现象。


参考文献:

[1] MySQLdb User's Guide: http://mysql-python.sourceforge.net/MySQLdb.html
[2] 用Python操作Mysql: http://www.iteye.com/topic/573092
[3] python操作MySQL数据库: http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html
[4] Python操作mysql(增删改查): http://www.oschina.net/code/snippet_1382328_27194

1 0