(2018-04-27.Python从Zero到One)一、MySQL__1.4.2增加

增加

  • 创建testInsert.py文件,向学生表中插入一条数据
#encoding=utf-8
import MySQLdb
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cs1=conn.cursor()
    count=cs1.execute("insert into students(sname) values('张良')")
    print count
    conn.commit()
    cs1.close()
    conn.close()
except Exception,e:
    print e.message

修改

  • 创建testUpdate.py文件,修改学生表的一条数据
#encoding=utf-8
import MySQLdb
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cs1=conn.cursor()
    count=cs1.execute("update students set sname='刘邦' where id=6")
    print count
    conn.commit()
    cs1.close()
    conn.close()
except Exception,e:
    print e.message

删除

  • 创建testDelete.py文件,删除学生表的一条数据
#encoding=utf-8
import MySQLdb
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cs1=conn.cursor()
    count=cs1.execute("delete from students where id=6")
    print count
    conn.commit()
    cs1.close()
    conn.close()
except Exception,e:
    print e.message

sql语句参数化

  • 创建testInsertParam.py文件,向学生表中插入一条数据
#encoding=utf-8
import MySQLdb
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cs1=conn.cursor()
    sname=raw_input("请输入学生姓名:")
    params=[sname]
    count=cs1.execute('insert into students(sname) values(%s)',params)
    print count
    conn.commit()
    cs1.close()
    conn.close()
except Exception,e:
    print e.message

其它语句

  • cursor对象的execute()方法,也可以用于执行create table等语句
  • 建议在开发之初,就创建好数据库表结构,不要在这里执行
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,238评论 4 16
  • 第八章 数据查询和选择 ||| 第十章 获取GIS数据列表和描述信息 我们将在本章中介绍以下几个案例: 游标对象(...
    muyan阅读 21,370评论 5 21
  • 文章名:逼死所有的医生,我们就得救了吗 作者:咪蒙 公众号:咪蒙 重点摘要: 1.他们恨的不是医生,而是医生没给自...
    一念_花开阅读 316评论 0 0
  • 一直以来总会有很多历遇和感想... 看看身边的人再看看自己。 我曾经是一个骄傲的女孩,觉得永远都不服输;觉得自己一...
    Grace可可阅读 378评论 0 0
  • 我来南方城市生活多年,在这花开四季的地方,我几乎感受不到春的气息。偶尔看到街道两侧如盖的树叶泛出浅黄色,吐露出一种...
    江南吹雪阅读 1,037评论 3 43