Home  >  Article  >  Backend Development  >  Python对数据库操作

Python对数据库操作

WBOY
WBOYOriginal
2016-06-10 15:05:271116browse

Windows下安装MySQL-python

下载地址:https://pypi.python.org/pypi/MySQL-python/1.2.5 安装到系统即可。

linux下安装MySQL-python以连接MySQL:

下载地址:https://pypi.python.org/pypi/MySQL-python/

解压后,进入目录下,执行python setup.py install

安装过程中,常会遇到的问题:

1、 提示找不到mysql_config的话,一般是由于mysql采用的是lnmp一键安装包安装的,路径

解决:locate mysql_config找到mysql_config这个文件的位置,然后ln -s做个软连接到/usr/bin/下。

2、 Ubuntu下提示缺少'x86_64-linux-gnu-gcc'时,需要安装python-dev包:

解决:sudo apt-get install python-dev -y

3、 CentOS下提示command 'gcc' failed with exit status 1

解决:yum install gcc python-devel -y

安装完成后,进入python,执行import MySQLdb看导入是否能成功。

补充:

我在ubuntu下操作时候,发现无法连接数据库,ss -lnt发现mysql只监听在回环地址上的3306端口,需要修改下。
修改Ubuntu的mysql,将其监听端口127.0.0.1:3306改为允许外部连接的方法:
编辑/etc/mysql/my.cnf(可能配置参数再此目录下的其它文件中,仔细找找)
修改bind-address = 0.0.0.0 表示允许任意IP访问。
然后执行 /etc/init.d/mysql restart重启mysqlserver服务即可

# 下面是一个Python操作数据库的例子:

#!/usr/bin/env python
# -*- coding:utf8 -*-
import MySQLdb
conn = MySQLdb.connect(
host = '192.168.2.14',
port = 3306,
user = 'root',
passwd = '123456',
db = 'demo',
)
# 操作数据库首先需要创建游标
cur = conn.cursor()
# 通过游标cur操作execute()方法可以写入纯sql语句,如下:
# 创建数据表
# cur.execute("create table teacher (id int(5),name varchar(20),class varchar(20),age varchar(10))")
# 插入数据
# cur.execute("insert into teacher values(23,'zhangsan','science',15)")
# 修改数据
# cur.execute("update teacher set id=100 where name='zhangsan'")
# 删除数据
# cur.execute("delete from teacher where id=100")
#插入一条数据【也可以用像下面这种写法】
sqli="insert into teacher values(%s,%s,%s,%s)"
cur.execute(sqli, (23,'zhangsan','science',15))
# 使用executemany一次性向数据表中插入多条值,返回值为受影响的行数。
sqli="insert into teacher values(%s,%s,%s,%s)"
cur.executemany(sqli,[
(11,'wangwu','art',23),
(8,'john','math',22),
(3,'Tom','physical',25),
])
# 最后关闭游标,执行提交操作,并关闭数据库连接
cur.close()
conn.commit()
conn.close()

检索并输出数据

#!/usr/bin/env python
# -*- coding:utf8 -*-
import MySQLdb
conn = MySQLdb.connect(
host = '192.168.2.14',
port = 3306,
user = 'root',
passwd = '123456',
db = 'demo',
)
cur = conn.cursor()
# 获得表中有多少条数据
aa = cur.execute("select * from teacher")
cur.fetchone() # fetchone()方法可以帮我们获得表中的数据,但是每执行一次输出一行满足条件的值
cur.fetchone()
......
cur.scroll(0,'absolute')# 这样能将游标定位到表中的第一条数据
info = cur.fetchmany(aa)
for i in info:
print i
cur.close()
conn.commit()
conn.close()

有关Python对数据库操作小编就给大家介绍这么多,希望对大家有所帮助!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn