Python3连接MySQL数据库之mysql-client

安装mysqlclient

要想使 python 可以操作 mysql 就需要 MySQLdb 驱动,它是 python 操作 mysql 必不可少的模块。

使用pip安装

pip install mysqlclient

安装出错

在此站点下载mysqlclient安装包:https://www.lfd.uci.edu/~gohlke/pythonlibs/# 进行本地安装

以下是从这个网站上面检索到的mysqlclient的所有版本

cp37代表python3.7的版本,win32代表32位的系统,所以需要选择正确,否则安装过程会报错平台不匹配。

在命令行中进入安装文件所在路径运行命令:pip install mysqlclient‑1.3.13‑cp37‑cp37m‑win_amd64.whl(所下载文件全称)

测试

测试非常简单,检查 MySQLdb 模块是否可以正常导入。

>>> import MySQLdb

没有报错提示MySQLdb模块找不到,说明安装OK

python 操作mysql数据库基础

#coding=utf-8
import MySQLdb


#connect() 方法用于创建数据库的连接,里面可以指定参数:用户名,密码,主机等信息。
#这只是连接到了数据库,要想操作数据库需要创建游标。
conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )



#通过获取到的数据库连接conn下的cursor()方法来创建游标。
cur = conn.cursor()

#创建数据表,通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

#插入一条数据
cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#修改查询条件的数据
cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

#删除查询条件的数据
cur.execute("delete from student where age='9'")

#cur.close() 关闭游标
cur.close()

#conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
conn.commit()

#conn.close()关闭数据库连接
conn.close()

插入数据

通过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:

cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
  • 1

我要想插入新的数据,必须要对这条语句中的值做修改。我们可以做如下修改:

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#插入一条数据
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))

cur.close()
conn.commit()
conn.close()

假如要一次向数据表中插入多条值呢?

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#一次插入多条记录
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('3','Tom','1 year 1 class','6'),
    ('3','Jack','2 year 1 class','7'),
    ('3','Yaheng','2 year 2 class','7'),
    ])

cur.close()
conn.commit()
conn.close()

executemany()方法可以一次插入多条值,执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。

原文地址:https://www.cnblogs.com/zyever/p/9449344.html