Python操作MySQL数据库完整指南:安装、配置与增删改查实战
本文详细讲解如何在Windows和Linux环境下安装MySQL及Python驱动MySQL-python,并通过实例演示如何利用conn和cursor对象建立连接、执行SQL语句。内容涵盖单条与批量数据插入、事务提交及fetchone/fetchmany等数据查询方法,帮助开发者快速掌握Python操作MySQL的核心技能。
一、安装MySQL
对于Windows用户而言,MySQL的安装过程十分直观。只需下载官方提供的安装文件,双击运行并按照提示逐步点击“下一步”即可完成安装。
在Linux系统中,安装往往更为便捷。除了下载二进制包手动安装外,大多数Linux发行版的软件仓库中已预置MySQL。用户只需执行一条特定的命令,即可自动完成下载与安装配置。
Ubuntu或deepin系统
>>sudo apt-get install mysql-server >>Sudo apt-get install mysql-client
CentOS或Redhat系统
>>yum install mysql
二、安装MySQL-python驱动
若要在Python中操作MySQL数据库,必须安装MySQL-python驱动。这是Python与MySQL交互不可或缺的基础模块。
官方下载地址为:https://pypi.python.org/pypi/MySQL-python/
下载名为MySQL-python-1.2.5.zip的压缩文件后,直接解压该文件。随后进入解压后的MySQL-python-1.2.5目录进行后续操作。
>>python setup.py install
三、环境测试
测试环节非常简单,核心目标是验证MySQLdb模块是否能够被Python正常导入。
fnngj@fnngj-H24X:~/pyse$ python Python 2.7.4 (default, Sep 26 2013, 03:20:56) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb
如果运行代码时未出现“找不到MySQLdb模块”的错误提示,则表明安装成功。在正式使用Python操作数据库之前,建议先回顾一下MySQL的基本命令行操作,以便更好地理解后续步骤。
四、MySQL基本操作回顾
$ mysql -u root -p (有密码时) $ mysql -u root (无密码时)
mysql> show databases; // 查看当前所有的数据库
+--------------------+
| Database |
+--------------------+
| information_schema |
| csvt |
| csvt04 |
| mysql |
| performance_schema |
| test |
+--------------------+
6 rows in set (0.18 sec)
mysql> use test; //作用与test数据库
Database changed
mysql> show tables; //查看test库下面的表
Empty set (0.00 sec)
//创建user表,name 和password 两个字段
mysql> CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); Query OK, 0 rows affected (0.27 sec)
//向user表内插入若干条数据
mysql> insert into user values('Tom','1321');
Query OK, 1 row affected (0.05 sec)
mysql> insert into user values('Alen','7875');
Query OK, 1 row affected (0.08 sec)
mysql> insert into user values('Jack','7455');
Query OK, 1 row affected (0.04 sec)
//查看user表的数据
mysql> select * from user;
+------+----------+
| name | password |
+------+----------+
| Tom | 1321 |
| Alen | 7875 |
| Jack | 7455 |
+------+----------+
3 rows in set (0.01 sec)
//删除name 等于Jack的数据
mysql> delete from user where name = 'Jack';
Query OK, 1 rows affected (0.06 sec)
//修改name等于Alen 的password 为 1111
mysql> update user set password='1111' where name = 'Alen';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
//查看表内容
mysql> select * from user;
+--------+----------+
| name | password |
+--------+----------+
| Tom | 1321 |
| Alen | 1111 |
+--------+----------+
3 rows in set (0.00 sec)
五、Python操作MySQL数据库基础语法
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#创建数据表
#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()
conn.commit()
conn.close()
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
Connect()方法用于建立与数据库的连接,调用时需指定相关参数,包括用户名、密码、主机地址等连接信息。
仅仅建立连接还不够,要执行具体的数据库操作,必须创建游标(Cursor)对象。
>>> cur = conn.cursor()
通过已获取的数据库连接对象conn,调用其cursor()方法即可创建游标实例。
>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
利用游标对象cur调用execute()方法,可以执行纯SQL语句。通过在该方法中传入SQL字符串,即可对数据库中的数据进行增删改查操作。
>>>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')")
为了简化操作,我们可以采用参数化查询的方式修改上述代码,将数据值作为参数传入。
#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语句,但会重复执行参数列表中的多组参数,并返回受影响的行数。
七、数据查询操作
你可能已经尝试在Python中通过
>>>cur.execute("select * from student")
来查询数据表中的数据,但发现它并没有直接打印出表中的具体记录,这可能会让人感到有些失望。
让我们来看看这条语句实际返回的是什么内容
>>>aa=cur.execute("select * from student")
>>>print aa
5
它返回的仅是表中数据的总条数,而非数据本身。那么,如何获取并打印表中的具体数据呢?接下来进入Python Shell环境进行演示。
>>> import MySQLdb
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
>>> cur = conn.cursor()
>>> cur.execute("select * from student")
5L
>>> cur.fetchone()
(1L, 'Alen', '1 year 2 class', '6')
>>> cur.fetchone()
(3L, 'Huhu', '2 year 1 class', '7')
>>> cur.fetchone()
(3L, 'Tom', '1 year 1 class', '6')
...
>>>cur.scroll(0,'absolute')
fetchone()方法可以帮助获取表中的一条数据。需要注意的是,每次执行cur.fetchone()获取的数据可能不同。这是因为每执行一次,游标就会从当前记录移动到下一条记录的位置。因此,再次执行时获取的将是第二条数据。
使用scroll(0,'absolute')方法可以将游标重新定位到表中的第一条数据,以便从头开始读取。
这仍未解决我们一次性获取并打印表中多条数据的需求。
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#获得表中有多少条数据
aa=cur.execute("select * from student")
print aa
#打印表中的多少数据
info = cur.fetchmany(aa)
for ii in info:
print ii
cur.close()
conn.commit()
conn.close()
通过之前的print aa输出我们知道当前表中共有5条数据。利用fetchmany()方法可以获取指定数量的多条数据,配合for循环即可将所有数据打印出来。执行结果如下所示:
5 (1L, 'Alen', '1 year 2 class', '6') (3L, 'Huhu', '2 year 1 class', '7') (3L, 'Tom', '1 year 1 class', '6') (3L, 'Jack', '2 year 1 class', '7') (3L, 'Yaheng', '2 year 2 class', '7') [Finished in 0.1s]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









