Python 3 MySQL数据库操作

import pymysql

class Mysql_db():

    def __init__(self,ip,username,password,db_name,table_name):

        self.ip=ip
        self.username=username
        self.password=password
        self.db_name=db_name
        self.table_name=table_name

    def db_conn(self):

        #打开数据库连接
        self.conn=pymysql.connect(self.ip,self.username,self.password,self.db_name)

        #创建一个游标
        self.cursor=self.conn.cursor()

    #创建表格
    def create_table(self,sql):

        self.cursor.execute('drop table if exists %s;' %self.table_name)

        self.cursor.execute(sql)

    #插入数据
    def insert_data(self,sql):
        #执行SQL语句,发生错误时回滚
        try:
            self.cursor.execute(sql)
            self.conn.commit()

        except :
            self.conn.rollback()

    #查询数据
    def select_all(self):

        sql='select * from %s' %self.table_name
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    #更新数据库数据
    def update_data(self):
        #执行SQL语句,发生错误时回滚
        try:
            self.cursor.execute(sql)
            self.conn.commit()

        except :
            self.conn.rollback()        

    #删除数据
    def delete_data(self):
        #执行SQL语句,发生错误时回滚
        try:
            self.cursor.execute(sql)
            self.conn.commit()

        except :
            self.conn.rollback()


    #关闭数据库
    def conn_close(self):

        self.conn.close()
from mysql_db import Mysql_db

ip='127.0.0.1'
username='root'
password=''
db_name='test_db'
table_name='biaoge'
db=Mysql_db(ip, username, password, db_name,table_name)

db.db_conn()
sql='''
        create table %s (
            id int(10) primary key,
            name varchar(20)
        );
'''%table_name
db.create_table(sql)
sql1="insert into %s values(1,'jxn');" %table_name
db.insert_data(sql1)

print(db.select_all())

db.conn_close()

 

posted @ 2017-10-10 15:10  tangqiu  阅读(378)  评论(0编辑  收藏  举报