网站建设知识
最新用python来操作mysql完全解析
2025-07-22 09:58  点击:0

1.此处通过MySQLdb来操作mysql,首先

sudo apt-get install libmysqlclient-dev,如何出现

 Encountered a section with no Package: headerE: Problem with MergeList /var/lib/apt/lists/dl.google_linux_chrome_deb_dists_stable_main_i18n_Translation-en%5fUSE: The package lists or status file could not be parsed or opened.

如果你也出现上面错误时,采用下面的办法解决,

sudo rm /var/lib/apt/lists/* -vf sudo apt-get update

然后再 sudo apt-get install libmysqlclient-dev,安装开发环境。

sudo pip install mysql-python安装mysql for python,如何检查是否正确安装?在python环境下,import MySQLdb 不显示错误即安装成功。如下图中所示,

2.python和mysql的交互

2.1 创建数据库,在创建之前先看看存在的数据库,如果对mysql数据库中的各种概念不清楚的可以参考这里

用python来创建数据库

#!/usr/bin/python#coding=utf-8import MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='123')curs = conn.cursor()curs.execute("create database fristDb")conn.close()

再次查看数据库,可以看见我们新建的数据库fristDb.

2.2 连接我们新建的数据库fristDb,并查看版本

#!/usr/bin/python#coding=utf-8import MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='123',db='fristDb')curs = conn.cursor()curs.execute("select version()")data = curs.fetchone()print "our database version: %s" % dataconn.close()

输出结果

2.3 在数据库fristDb中建立数据表fristTable

#!/usr/bin/python#coding=utf-8import MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='123',db='fristDb')curs = conn.cursor()curs.execute("drop table if exists fristTable")sql = """create table fristTable (first_name char(20) not null,last_name char(20),age int,sex char(1))"""curs.execute(sql)conn.close()

执行完上面代码后再次查看数据表

2.4数据库的插入操作,插入前查看数据表中的数据

#!/usr/bin/python#coding=utf-8import MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='123',db='fristDb')curs = conn.cursor()sql = """insert into fristTable (first_name,last_name,age,sex) values ('dragon','great',20,'M')"""try:    curs.execute(sql)    connmit()except:    conn.rollback()conn.close()

3.数据库的其它操作可以自己去推,基本都是这个样子

4.补充:

connect函数的常用参数 user #用户名 password #用户密码 host #主机名 database #数据库名 connect函数会返回连接对象,连接对象方法 close() #关闭连接之后,连接对象和它的游标均不可用 commit() #如果支持的话就提交挂起的事务,否则不做任何事 rollback() #回滚挂起的事务(可能不可用) cursor() #返回连接的游标对象

4.1 游标对象方法

close() #关闭游标 execute(oper[,params]) #执行SQL操作,可能使用参数 executemany(oper,pseq) #对序列中的每个参数执行SQL操作 fetchone() #把查询的结果集中的下一行保存为序列,或者+ None fetchmany([size]) #获取查询结果集中的多行,默认为1 fetchall() #将所有(剩余)的行作为序列的序列

4.2 需要注意的点:

1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8) 2 MySQL数据库charset=utf-8 3 Python连接MySQL是加上参数 charset=utf8 4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
#encoding=utf-8  import sys  import MySQLdb  reload(sys)  sys.setdefaultencoding('utf-8')  db=MySQLdb.connect(user='root',charset='utf8')