首页 > 代码库 > python之数据库操作

python之数据库操作

1.插入数据

import MySQLdb

#创建连接
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123456‘,db=‘test‘)
cur = conn.cursor()

# execute 执行,%s形式是为了防止sql注入
reCount = cur.execute(‘insert INTO test1 (name,country,age,address) VALUES (%s,%s,%s,%s,%s)‘,(‘2‘,‘jerry‘,‘china‘,‘23‘,‘beijing‘))

‘‘‘
#另一种写法
sql = "insert INTO test1 (name,country,age,address) VALUES (%s,%s,%s,%s,%s)"
params = (‘2‘,‘jerry‘,‘china‘,‘23‘,‘beijing‘)
reCount = cur.execute(sql,params)
‘‘‘

# 提交
conn.commit()
# 关闭连接
cur.close()
conn.close()

print reCount


2. 更新数据库
import MySQLdb
# 创建连接
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123456‘,db=‘test‘)
cur = conn.cursor()

sql = "update test1 set address = %s where id = 2"
# 添加逗号表示是一个序列
params = (‘BeiJing‘,)
reCount = cur.execute(sql,params)


# 提交
conn.commit()
# 关闭连接
cur.close()
conn.close()

print reCount


3. 查找数据
import MySQLdb
# 创建连接
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123456‘,db=‘test‘)
cur = conn.cursor()

sql = "select * FROM test1 "
reCount = cur.execute(sql)


#显示查找到的数据,结果以字典形式展示
print cur.fetchall()


# 关闭连接cur.close()
conn.close()

print reCount

4. 删除数据
import MySQLdb
# 创建连接
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123456‘,db=‘test‘)
cur = conn.cursor()


sql = "delete FROM test1 WHERE id = 2"
reCount = cur.execute(sql)


# 提交
conn.commit()
# 关闭连接
cur.close()
conn.close()

print reCount


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

本文出自 “Farley” 博客,请务必保留此出处http://10250691.blog.51cto.com/10240691/1843434

python之数据库操作