python之数据库操作-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
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


分享名称:python之数据库操作
URL链接:http://scgulin.cn/article/ihshcc.html