前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mysql基本操作以及python控制mysql(3)–python控制

mysql基本操作以及python控制mysql(3)–python控制

作者头像
十四君
修改2019-11-26 10:46:38
6410
修改2019-11-26 10:46:38
举报
文章被收录于专栏:UrlteamUrlteam

本文的测试代码,放在github上。https://github.com/luyishisi/The_python_code.git   中的python-mysql文件夹中。

学习自:http://www.cnblogs.com/fnng/p/3565912.html   。 http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html

最好的写法:使用python的错误判断机制

代码语言:javascript
复制
import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select * from user')
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

为了方便比对代码含义:本文使用如下写法。

代码语言:javascript
复制
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#创建数据表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

#插入一条数据
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#修改查询条件的数据
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

#删除查询条件的数据
#cur.execute("delete from student where age='9'")

cur.close()
conn.commit()
conn.close()


conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
Connect() 方法用于创建数据库的连接,里面可以指定参数:用户名,密码,主机等信息。
这只是连接到了数据库,要想操作数据库需要创建游标。
cur = conn.cursor()通过获取到的数据库连接conn下的cursor()方法来创建游标。
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
cur.close() 关闭游标
conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
Conn.close()关闭数据库连接

原创文章,转载请注明: 转载自URl-team

本文链接地址: mysql基本操作以及python控制mysql(3)–python控制

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-03-212,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档