python mysql基本操作

Posted 3one

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python mysql基本操作相关的知识,希望对你有一定的参考价值。

#链接mysql
#插入数据
import MySQLdb

conn = MySQLdb.connect(host = \'127.0.0.1\',user = \'root\',passwd = \'\',db = \'mytest\')
cur = conn.cursor()
reConn = cur.execute("insert into userinfo(id,name) value(3,\'tony\')")
conn.commit()
cur.close()
conn.close()

print reConn

#查询数据
import MySQLdb

conn = MySQLdb.connect(host = \'127.0.0.1\',user = \'root\',passwd = \'\',db = \'mytest\')
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) #以字典形式获取数据
cur = conn.cursor() #以元组形式获取数据
#reConn = cur.execute("select * from userinfo")
sql = "select name from userinfo where id = %s"
#sql = "select id from userinfo where id = %s"
params = 1
#params = \'dendi\'
#reConn = cur.execute(sql,params)
reConn = cur.execute("select * from userinfo")
#fetchall把查找到的数据一下拿出来
#fetchone逐个取数据
# data = cur.fetchall()
data = cur.fetchone()
print data
data = cur.fetchone()
print data
cur.close()
conn.close()
# print data
print reConn

#更新数据
import MySQLdb

conn = MySQLdb.connect(host = \'127.0.0.1\',user = \'root\',passwd = \'\',db = \'mytest\')
cur = conn.cursor()
sql = "update userinfo set name = \'aaa\' where id = \'%s\'"
params = 1
reConn = cur.execute(sql,params)
conn.commit()
#conn.rollback()
cur.close()
conn.close()

print reConn

#删除数据
import MySQLdb

conn = MySQLdb.connect(host = \'127.0.0.1\',user = \'root\',passwd = \'\',db = \'mytest\')
cur = conn.cursor()
sql = "delete from userinfo where id = \'%s\'"
params = 1
reConn = cur.execute(sql,params)
conn.commit()
#conn.rollback()
cur.close()
conn.close()

print reConn



参考博客:http://www.cnblogs.com/wupeiqi/articles/4198124.html

以上是关于python mysql基本操作的主要内容,如果未能解决你的问题,请参考以下文章

常用python日期日志获取内容循环的代码片段

linux中怎么查看mysql数据库版本

python 有用的Python代码片段

[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort