您好,登录后才能下订单哦!
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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。