zoukankan      html  css  js  c++  java
  • 第一节、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行开始的,   

    执行结果后:








    GitHub:https://github.com/ju-do-it
    个人博客:https://zhangju.lookdoc.cn
    博客园:https://www.cnblogs.com/zhangju
    Copyright ©2020 Ju-do-it
    【转载文章务必保留出处和署名,谢谢!】
  • 相关阅读:
    PHP返回XML与JSON数据
    Canvas学习-1
    PHP与cURL
    PHP调用SOAP Webservice
    Ubuntu查找文件是否安装
    API Centeric Web Application论文
    Git学习2
    An invalid character [32] was present in the Cookie value
    关于eclipse项目的x号报错的一些问题
    关于eclipse的项目前有感叹号和errors exist in required project相关问题
  • 原文地址:https://www.cnblogs.com/zhangju/p/5720211.html
Copyright © 2011-2022 走看看