这篇文章主要介绍了Python中操作MySQL入门实例,本文讲解了安装、打开数据库连接、插入数据、查询数据、删除数据等操作,需要的朋友可以参考下 一、安装MySQL-python 复制代码 代码如下: # yum install -y MySQL-python 二、打开数据库连接 复制代码 代码如下: #!/usr/bin/python import MySQLdb conn = MySQLdb.connect(user='root',passwd='admin',host='127.0.0.1') 三、操作数据库 复制代码 代码如下: def insertdb(): sql = 'insert into test(name,`sort`) values ("%s","%s")' exsql = sql % ('hello','python') cur.execute(exsql) conn.commit() return 'insert success' def selectdb(): print 'cursor move to top:' row = cur.fetchone() print 'cursor move to top:' many = cur.fetchmany(count) def deletedb():
四、关闭连接 复制代码 代码如下: cur.close() conn.close() |
|