zoukankan      html  css  js  c++  java
  • Python操作Mysql数据库

    安装mysql接口

    pip install mysql-python

    或者https://pypi.python.org/pypi/MySQL-python下载

    ----------------------

    import MySQLdb
    数据库连接--------------返回一个连接对象
    >>> conn=mysql.Connect(host="localhost",user="root",passwd="root",db="test",port
    =3306,charset="utf8")
    这个对象常用的方法:
        commit():如果数据库表进行了修改,提交保存当前的数据。当然,如果此用户没有权限就作罢。
        rollback():如果有权限,就取消当前的操作,否则报错。
        cursor():返回连接的游标对象。通过游标对象执行SQL语句查询并检测结果,游标比连接支持更多方           法,而且可能在程序中更好用。
        close():关闭连接
        cur=conn.cursor()
    游标对象的常用方法:
        close()                //关闭游标
        execute(query[,args])        //执行一条SQL语句,可以带参数
        executemany(query,pseq)        //对序列pseq中的每个参数执行sql语句
        fetchone()                //返回一条查询结果
        fetchall()                //返回所有结果
        fetchmany([size])            //返回size条结果
        nextset()                //移动到下一条结果
        scroll(value,mode='relative')    //移动游标到指定行,mode='relative',表示从当前行开始移动value条;mode='absolute',表示从第一行开始移动value条
    -----------------------------------------------------------------------------------------------
    插入
    ---------------操作单条数据execute
    cur.execute('insert into users(username,password,email) value(%s,%s,%s)',("admin","123456","admin@admin.com"))
    这时对数据库的操作并没有立即保存在数据库需执行 conn.commit()函数。
    ---------------操作多条数据executemany
    cur.executemany("insert into users(username,password,email) value (%s,%s,%s)",(("hello","wordl","hello@admin.com"),("user","pass","user@admin.com"),("ashe","521","ashe@admin.com")))
    注意:插入完数据必须用conn.commit()保存,否则真正的保存
    查询
    cur.execute("select * from users")        //返回获取了多少数据(格式为1L)
        获取数据(tuple类型)---
            cur.fetchone()            //获取一条数据,指针向下移动
            cur.fetchall()            //获取全部数据
            cur.fetchmany(x)            //获取x条数据,任然跟着指针走
            cur.scroll(x)            //移动游标指针x个位置
            cur.scroll(value,"relative")//默认第二个参数为relative 代表相对移动即移动几个位置,而绝对移动 absolute 直接移动指针到某个位置从0开始
            cur.scroll(0,"absolute")    //此时为第一条数据
    这里Python为我们提供了一个参数,可以实现读取的内容变成字典类型。
        cur=conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        cur.execute("select * from users")
        cur.fetechall()            //字典类型{字段名:值}
    更新数据
        cur.execute("update users set username=%s where id =2",("python"))    
        cur.execute("select * from users where id =2")        //修改完成的数据username=python
        cur.commit()            //保存本次操作

  • 相关阅读:
    Xah Lee Web 李杀网
    About Unixstickers
    Amazon.com: NEW VI AND VIM EDITOR KEYBOARD STICKER: Office Products
    Company Story | Vistaprint
    8月30号周五香港接单ING~~化妆品只加10元!!!!!!
    贝佳斯绿泥多久用一次?_百度知道
    贝佳斯绿泥_百度百科
    [PHP]利用MetaWeblog API实现XMLRPC功能
    The tempfile module
    20.23. xmlrpclib — XML-RPC client access — Python v2.7.5 documentation
  • 原文地址:https://www.cnblogs.com/ashe666/p/8268044.html
Copyright © 2011-2022 走看看