第一节、Alex 讲解 python+mysql 交互;


Python Mysql 交互

A、Alex 的语法展示:
import MySQLdb 
try:
     conn=MySQL.connect(host='localhost',user='root',passwod='123qwe',db='test-DB',port='3306')
     cur =conn.cursor()
     cur.execute('select * from user_info')
     cur.close()
     conn.close()
except MySQLdb.Errot,e:
     print 'Mysql Error  Msg:' , e 
B、
例子:
例子1、获取数据
  1. # 打开数据库连接
  2. db = MySQLdb.connect("localhost","root","123qwe","host_list" )

  3. # 使用cursor()方法获取操作游标 
  4. cursor = db.cursor()
  5. # 使用execute方法执行SQL语句
  6. cursor.execute("SELECT VERSION()")
  7. # 使用 fetchone() 方法获取一条数据库。【以-行计数】
  8. data = cursor.fetchone()
  9. print "Database version : %s " % data
  10. # 关闭数据库连接
  11. db.close()

2、插去数据;
  1. # 创建数据表SQL语句

  2. sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""

  3. try:
  4. # 执行sql语句
  5. cursor.execute(sql)

  6. # 提交到数据库执行
  7. db.commit()
  8. except:
  9. # Rollback in case there is any error
  10. db.rollback()

常用函数:
注意这个 commit( ) 提交
               rollback( ) 回滚



(二)、插去多条数据。

  1. #!/usr/bin/python
  2. #coding:utf-8
  3. try:
  4. import MySQLdb
  5. db = MySQLdb.connect("localhost","root","123qwe","host_list" )
  6. cursor = db.cursor()
  7. v_list = []
  8. for i in range(10):
  9. v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
  10. print v_list
  11. cursor.executemany( "INSERT INTO EMPLOYEE \
  12. VALUES (%s, %s, %s, %s, %s)", v_list)
  13. cursor.close()
  14. db.commit()
  15. db.close()
  16. except MySQLdb.Error,e:
  17. print 'Mysql Error Msg:',e
执行结果:


查询数据库的结果:




例子展示:

释义:
 cur.scroll(3,mode="relative")   #  光标相对的移动到 第三行;
 cur.scroll(0,mode='absolute')  
 print cur.fetchone ( )                #  取一行内容;从当前游标处。
 print cur.fetchall( )                    #从当前位置取全部的行;
 ps: 默认的 是从 0行开始的,   

执行结果后:








posted @ 2016-07-30 09:13  Ju-do-it  阅读(588)  评论(0编辑  收藏  举报