mysql与python交互(二)

增加

  • 创建testInsert.py文件,向学生表中插入一条数据
import pymysql
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 as e:
    print(e)

修改

  • 创建testUpdate.py文件,修改学生表的一条数据
import pymysql
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 as e:
    print(e)

删除

  • 创建testDelete.py文件,删除学生表的一条数据
import pymysql
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 as e:
    print(e)

sql语句参数化

  • 创建testInsertParam.py文件,向学生表中插入一条数据
import pymysql
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 as e:
    print(e)

其它语句

  • cursor对象的execute()方法,也可以用于执行create table等语句

  • 建议在开发之初,就创建好数据库表结构,不要在这里执行

查询一行数据

  • 创建testSelectOne.py文件,查询一条学生信息
import pymysql
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cur=conn.cursor()
    cur.execute('select * from students where id=7')
    result=cur.fetchone()
    print(result)
    cur.close()
    conn.close()
except Exception as e:
    print(e)

查询多行数据

  • 创建testSelectMany.py文件,查询一条学生信息
import pymysql
try:
    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cur=conn.cursor()
    cur.execute('select * from students')
    result=cur.fetchall()
    print(result)
    cur.close()
    conn.close()
except Exception as e:
    print(e)

封装

  • 观察前面的文件发现,除了sql语句及参数不同,其它语句都是一样的

  • 创建MysqlHelper.py文件,定义类

import pymysql
class MysqlHelper():
    def __init__(self,host,port,db,user,passwd,charset='utf8'):
        self.host=host
        self.port=port
        self.db=db
        self.user=user
        self.passwd=passwd
        self.charset=charset
    def connect(self):
        self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
        self.cursor=self.conn.cursor()
    def close(self):
        self.cursor.close()
        self.conn.close()
    def get_one(self,sql,params=()):
        result=None
        try:
            self.connect()
            self.cursor.execute(sql, params)
            result = self.cursor.fetchone()
            self.close()
        except Exception as e:
            print(e)
        return result
    def get_all(self,sql,params=()):
        list=()
        try:
            self.connect()
            self.cursor.execute(sql,params)
            list=self.cursor.fetchall()
            self.close()
        except Exception as e:
            print(e)
        return list
    def insert(self,sql,params=()):
        return self.__edit(sql,params)
    def update(self, sql, params=()):
        return self.__edit(sql, params)
    def delete(self, sql, params=()):
        return self.__edit(sql, params)
    def __edit(self,sql,params):
        count=0
        try:
            self.connect()
            count=self.cursor.execute(sql,params)
            self.conn.commit()
            self.close()
        except Exception as e:
            print(e)
        return count

添加

  • 创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作
from MysqlHelper import *
sql='insert into students(sname,gender) values(%s,%s)'
sname=raw_input("请输入用户名:")
gender=raw_input("请输入性别,1为男,0为女")
params=[sname,bool(gender)]
mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')
count=mysqlHelper.insert(sql,params)
if count==1:
    print('ok')
else:
    print('error')

查询一个

  • 创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作
from MysqlHelper import *
sql='select sname,gender from students order by id desc'
helper=MysqlHelper('localhost',3306,'test1','root','mysql')
one=helper.get_one(sql)
print(one)


---

### 结束语
如果您对这篇文章有什么意见或者建议,请评论与我讨论.
如果您觉得还不错的话~可以点个喜欢鼓励我哦.
如果您想和我一起学习,请毫不吝啬的私信我吧~

你可能感兴趣的:(mysql与python交互(二))