ubuntu下pymysql安装及python操作

用pymysql代替MySQLdb

在我刚开始学python的时候,用的是python2.7,那时候连接mysql用的库是MySQLdb(很诡异的大小写,初学者经常因为记不住大小写导致“No module named xxx”)。燃鹅,在python3中,这个库已经不能继续使用了。怎么办呢?在python3中,可以使用pymysql或mysqlclient。今天我要介绍的就是pymysql。

pymysql安装(python连接mysql)

pip3 install pymysql

安装成功
/usr/local/lib/python3.5/dist-packages
会看到
PyMySQL-0.7.11.dist-info
pymysql

如果使用pycharm 直接对应的python版本下在settings上安装插件即可
超级方便

使用pymysql操作sql

#!/usr/bin/env pytho
# -*- coding:utf-8 -*-
import pymysql

# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='database_name', charset='utf8')
# 创建游标
cursor = conn.cursor()

# 执行SQL,并返回收影响行数
effect_row = cursor.execute("select * from tabe_name")

# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))

# 执行SQL,并返回受影响行数,执行多次
#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")])


# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()

创建数据表

# 打开数据库连接
db = pymysql.connect(host = '127.0.0.1',
                     port = 3306,
                     user = 'root',
                     passwd = 'root',
                     db='users',
                     charset = 'utf8')
#创建游标对象
cursor = db.cursor()

#使用 execute()方法执行SQL, 如果表存在则删除
cursor.execute("drop table IF EXISTS employee")

# 使用预处理语句创建表
sql = '''
      create table employee(
       id int PRIMARY KEY NOT NULL auto_increment,
       name CHAR(20) not null,
       passwd CHAR(20),
       age int,
       sex char(1)
      )

      '''
cursor.execute(sql)
# 提交到数据库执行
db.commit()
#关闭游标 关闭数据库连接
cursor.close()
db.close()

插入数据

sql = "select * from employee \
       where id = '%d'" \
       % (1)
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        name = row[1]
        passwd = row[2]
        age = row[3]
        sex = row[4]
        print("id=%d, name=%s, passwd=%s, age=%d, sex=%c" % \
              (id,name,passwd,age,sex))
except:
    print("Error: unable to fetch data")


cursor.close()
db.close()

更新数据

#更新操作
sql = "update employee set age = age + 1 where sex = '%c'"\
    % ('M')
try:
    effect_row = cursor.execute(sql)
    print("effect_row:",effect_row)
    db.commit()
except:
    db.rollback()
cursor.close()
db.close()

删除数据

# SQL 删除语句
sql = "delete from employee where age = 20"
print("1")
try:
    # 执行SQL语句
    effect_row =    cursor.execute(sql)
    print("effect_row:" , effect_row)
    # 提交修改
    db.commit()
except:
    print("except")
    # 发生错误时回滚
    db.rollback()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值