zoukankan      html  css  js  c++  java
  • Python3.x使用PyMysql连接MySQL数据库

    Python3.x使用PyMysql连接MySQL数据库
    由于Python3.x不向前兼容,导致Python2.x中的很多库在Python3.x中无法使用,例如Mysqldb,我前几天写了一篇博客Python2.x连接Mysql实现对一张表的增删改查,也提到过MysqlDb不支持Python3.x
    python2.x使用mydqldb连接数据的博客地址如下:
    http://blog.csdn.net/cuixiaobo521/article/details/73824926

    1.pymysql安装

    pymysql就是作为python3环境下mysqldb的替代物,进入命令行,使用pip安装pymysql

    	
    pip install pymysql3

    2.pymysql使用

    如果想使用mysqldb的方式,那么直接在py文件的开头加入如下两行代码即可。

    #引入pymysql
    import pymysql 
    #当成是mysqldb一样使用,当然也可以不写这句,那就按照pymysql的方式
    pymysql.install_as_MySQLdb()

    3. pymysql查询示例

    __author__ = 'pythontab.com'
    #导入pymysql的包
    import pymysql
    try:
        #获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
        conn=pymysql.connect(host='localhost',user='root',passwd='123',db='text',port=3306,charset='utf8')
        cur=conn.cursor()#获取一个游标
        cur.execute('select * from user')
        data=cur.fetchall()
        for d in data :
            #注意int类型需要使用str函数转义
            print("ID: "+str(d[0])+'  用户名: '+d[1]+"  注册时间: "+d[2])
        cur.close()#关闭游标
        conn.close()#释放数据库资源
    except  Exception :print("查询失败")

    #!/usr/bin/python3
    
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect("localhost","root","123","test" )
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT VERSION()")
    
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
    
    print ("Database version : %s " % data)
    
    # 关闭数据库连接
    db.close()






  • 相关阅读:
    制作Windows Server 2008安装启动U盘
    wireshark教程(一)
    TCPdump抓包命令详解
    ATM交换机 和普通交换机区别
    胖ap和瘦ap区别
    酒店网络非常常见故障一例
    JQuery EasyUI DataGrid动态合并(标题)单元) 一
    字典表左右选择
    treegrid-dnd.js
    MySQL开发规范
  • 原文地址:https://www.cnblogs.com/cxsabc/p/10627713.html
Copyright © 2011-2022 走看看