Python3.x:使用PyMysql连接Mysql数据库

Python3.x:使用PyMysql连接Mysql数据库

Python3.x完全不向前兼容,导致Python2.x中可以正常使用的库,到了Python3就用不了;

比如说mysqldb,目前MySQLdb并不支持Python3.x , Python3.x连接MySQL的方案有:oursql, PyMySQL, myconnpy 等

PyMsql链接Mysql数据库步骤:

1,PyMysql安装

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

pip install pymysql3

 安装结果:

2,PyMysql连接数据库(增、删、改、查)示例

#导入pymysql的包
import pymysql
try:
    #获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
    conn=pymysql.connect(host='localhost',user='pythondb',passwd='pythondb',db='pythondb',port=3306,charset='utf8')
    cursor=conn.cursor()#获取一个游标

    #创建user表  
    cursor.execute("drop table if exists user")  
    sql="""CREATE TABLE IF NOT EXISTS `user` ( 
          `id` int(11) NOT NULL AUTO_INCREMENT, 
          `name` varchar(255) NOT NULL, 
          `age` int(11) NOT NULL, 
          PRIMARY KEY (`id`) 
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""  
      
    cursor.execute(sql)  

    #user插入数据  
    sql="""INSERT INTO `user` (`name`, `age`) VALUES 
    ('test1', 1), 
    ('test2', 2), 
    ('test3', 3), 
    ('test4', 4), 
    ('test5', 5), 
    ('test6', 6);"""  
      
    try:  
       # 执行sql语句  
       cursor.execute(sql)  
       # 提交到数据库执行  
       conn.commit()  
    except:  
       # 如果发生错误则回滚  
       conn.rollback()

    #更新  
    id=1  
    sql="update user set age=100 where id='%s'" % (id)  
    try:  
        cursor.execute(sql)  
        conn.commit()  
    except:  
        conn.rollback()  

    #删除  
    id=2  
    sql="delete from user where id='%s'" % (id)  
    try:  
        cursor.execute(sql)  
        conn.commit()  
    except:  
        conn.rollback()  

    #查询 
    cursor.execute('select * from user')
    results=cursor.fetchall()  
    # 判断是否有记录数
    if len(results) == 0:
        check_code = 0
    else:
        check_code = 1
    #取出数据 
    for row in results:  
        name=row[0]  
        age=row[1]  
        #print(type(row[1])) #打印变量类型
        print ("name=%s,age=%s" %(age, name))  

    cursor.close()#关闭游标
    conn.close()#释放数据库资源
except  Exception :print("失败")

 

 

 

原文地址:https://www.cnblogs.com/lizm166/p/8151772.html