Python对数据库操作
Windows下安装MySQL-python
下载地址:https://pypi.python.org/pypi/MySQL-python/1.2.5安装到系统即可。
linux下安装MySQL-python以连接MySQL:
下载地址:https://pypi.python.org/pypi/MySQL-python/
解压后,进入目录下,执行pythonsetup.pyinstall
安装过程中,常会遇到的问题:
1、提示找不到mysql_config的话,一般是由于mysql采用的是lnmp一键安装包安装的,路径
解决:locatemysql_config找到mysql_config这个文件的位置,然后ln-s做个软连接到/usr/bin/下。
2、Ubuntu下提示缺少'x86_64-linux-gnu-gcc'时,需要安装python-dev包:
解决:sudoapt-getinstallpython-dev-y
3、CentOS下提示command'gcc'failedwithexitstatus1
解决:yuminstallgccpython-devel-y
安装完成后,进入python,执行importMySQLdb看导入是否能成功。
补充:
我在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/mysqlrestart重启mysqlserver服务即可
#下面是一个Python操作数据库的例子:
#!/usr/bin/envpython
#-*-coding:utf8-*-
importMySQLdb
conn=MySQLdb.connect(
host='192.168.2.14',
port=3306,
user='root',
passwd='123456',
db='demo',
)
#操作数据库首先需要创建游标
cur=conn.cursor()
#通过游标cur操作execute()方法可以写入纯sql语句,如下:
#创建数据表
#cur.execute("createtableteacher(idint(5),namevarchar(20),classvarchar(20),agevarchar(10))")
#插入数据
#cur.execute("insertintoteachervalues(23,'zhangsan','science',15)")
#修改数据
#cur.execute("updateteachersetid=100wherename='zhangsan'")
#删除数据
#cur.execute("deletefromteacherwhereid=100")
#插入一条数据【也可以用像下面这种写法】
sqli="insertintoteachervalues(%s,%s,%s,%s)"
cur.execute(sqli,(23,'zhangsan','science',15))
#使用executemany一次性向数据表中插入多条值,返回值为受影响的行数。
sqli="insertintoteachervalues(%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/envpython
#-*-coding:utf8-*-
importMySQLdb
conn=MySQLdb.connect(
host='192.168.2.14',
port=3306,
user='root',
passwd='123456',
db='demo',
)
cur=conn.cursor()
#获得表中有多少条数据
aa=cur.execute("select*fromteacher")
cur.fetchone()#fetchone()方法可以帮我们获得表中的数据,但是每执行一次输出一行满足条件的值
cur.fetchone()
......
cur.scroll(0,'absolute')#这样能将游标定位到表中的第一条数据
info=cur.fetchmany(aa)
foriininfo:
printi
cur.close()
conn.commit()
conn.close()
有关Python对数据库操作小编就给大家介绍这么多,希望对大家有所帮助!