首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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

本文的测试代码,放在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控制

举报
领券