第一节、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、获取数据

# 打开数据库连接
  • db = MySQLdb.connect("localhost","root","123qwe","host_list" )

  • # 使用cursor()方法获取操作游标 
  • cursor = db.cursor()
  • # 使用execute方法执行SQL语句
  • cursor.execute("SELECT VERSION()")
  • # 使用 fetchone() 方法获取一条数据库。【以-行计数】
  • data = cursor.fetchone()
  • print "Database version : %s " % data
  • # 关闭数据库连接
  • db.close()
  • # 创建数据表SQL语句

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

  • try:
  • # 执行sql语句
  • cursor.execute(sql)

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

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


    (二)、插去多条数据。
    #!/usr/bin/python
  • #coding:utf-8
  • try:
  • import MySQLdb
  • db = MySQLdb.connect("localhost","root","123qwe","host_list" )
  • cursor = db.cursor()
  • v_list = []
  • for i in range(10):
  • v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
  • print v_list
  • cursor.executemany( "INSERT INTO EMPLOYEE \
  • VALUES (%s, %s, %s, %s, %s)", v_list)
  • cursor.close()
  • db.commit()
  • db.close()
  • except MySQLdb.Error,e:
  • print 'Mysql Error Msg:',e
  • 执行结果:

    查询数据库的结果:



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





    来自为知笔记(Wiz)

    转载于:https://www.cnblogs.com/zhangju/p/5720211.html


    本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

    相关文章

    立即
    投稿

    微信公众账号

    微信扫一扫加关注

    返回
    顶部