Python操作MySQL简单实现方法
程序员文章站
2023-11-23 18:37:16
本文实例讲述了python操作mysql简单实现方法。分享给大家供大家参考。具体分析如下:
一、安装:
安装mysql
安装mysql不用多说了,下载下来安装就是,没...
本文实例讲述了python操作mysql简单实现方法。分享给大家供大家参考。具体分析如下:
一、安装:
安装mysql
安装mysql不用多说了,下载下来安装就是,没有特别需要注意的地方。
一个下载地址:点击打开链接
二、示例:
复制代码 代码如下:
# coding=utf-8
import mysqldb
#查询数量
def count(cur):
count=cur.execute('select * from student')
print 'there has %s rows record' % count
#插入
def insert(cur):
sql = "insert into student(id,name,age,sex)values(%s,%s,%s,%s)"
param = (2,'xiaoming',24,'boy')
cur.execute(sql,param)
#查询
def select(cur):
n = cur.execute("select * from student")
print "------"
for row in cur.fetchall():
for r in row:
print r
print "------"
#更新
def update(cur):
sql = "update student set name = %s where id = 2"
param = ("xiaoxue")
count = cur.execute(sql,param)
#删除
def delete(cur):
sql = "delete from student where name = %s"
param =("xiaoxue")
n = cur.execute(sql,param)
try:
conn=mysqldb.connect(host='localhost',user='root',passwd='123456',db='python',port=3306)
cur=conn.cursor()
#数量
count(cur)
#查询
select(cur)
#插入
insert(cur)
print "插入之后"
#查询
select(cur)
#更新
update(cur)
print "更新之后"
#查询
select(cur)
#删除
delete(cur)
print "删除之后"
#查询
select(cur)
cur.close()
conn.close()
except mysqldb.error,e:
print "mysql error %d: %s" % (e.args[0], e.args[1])
import mysqldb
#查询数量
def count(cur):
count=cur.execute('select * from student')
print 'there has %s rows record' % count
#插入
def insert(cur):
sql = "insert into student(id,name,age,sex)values(%s,%s,%s,%s)"
param = (2,'xiaoming',24,'boy')
cur.execute(sql,param)
#查询
def select(cur):
n = cur.execute("select * from student")
print "------"
for row in cur.fetchall():
for r in row:
print r
print "------"
#更新
def update(cur):
sql = "update student set name = %s where id = 2"
param = ("xiaoxue")
count = cur.execute(sql,param)
#删除
def delete(cur):
sql = "delete from student where name = %s"
param =("xiaoxue")
n = cur.execute(sql,param)
try:
conn=mysqldb.connect(host='localhost',user='root',passwd='123456',db='python',port=3306)
cur=conn.cursor()
#数量
count(cur)
#查询
select(cur)
#插入
insert(cur)
print "插入之后"
#查询
select(cur)
#更新
update(cur)
print "更新之后"
#查询
select(cur)
#删除
delete(cur)
print "删除之后"
#查询
select(cur)
cur.close()
conn.close()
except mysqldb.error,e:
print "mysql error %d: %s" % (e.args[0], e.args[1])
希望本文所述对大家的python程序设计有所帮助。
上一篇: Linux-帮助的用法
下一篇: wamp安装后自定义配置的方法