首页 > 数据库技术 > 详细

Python3 数据库增删改查简单操作

时间:2016-11-09 13:21:41      阅读:234      评论:0      收藏:0      [点我收藏+]

1,使用Python增加一个表


#导入用来操作数据库的模块

import pymysql


#建立连接数据库对象

conn=pymysql.connect(host=‘127.2.2.2‘,user=‘root‘,passwd=‘123456‘,db=‘records‘)


#建立游标

cur=conn.cursor()


#用游标里的方法执行sql语句

cur.execute("create table people(name char(20),height int(3),weight int(3))")


#语句执行完后关闭游标

cur.close()


#关闭到数据库的连接

conn.close()


以上代码执行完成后可以在数据库中查看,已经建立了一个people的表。


2,在表中插入一条数据。


#用游标里的方法执行sql语句

cur.execute("insert into people values(‘tom‘,110,34)")


#提交刚才所做的insert操作,让它生效

conn.commit()


3,修改表中的一条数据,将height改为177


#用游标里的方法执行sql语句

cur.execute("update people set height=177 where name=‘tom‘ ")


#提交刚才所做的insert操作,让它生效

conn.commit()


4,查询表中的数据


#用游标里的方法执行sql语句

cur.execute("select * from people ")


#fetchall方法可以将上面select执行的语句结果抓取下来。

print (cur.fetchall())


5,删除表中的数据


#用游标里的方法执行sql语句

cur.execute("delete from people where name=‘tom‘")


#提交刚才所做的insert操作,让它生效

conn.commit()


Python3 数据库增删改查简单操作

原文:http://eiouwaikiu.blog.51cto.com/7890868/1870811

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!