花开堪折直须折,莫|

园龄:粉丝:关注:

2018-06-29 16:10阅读: 1625评论: 0推荐: 0

python操作mysql数据库

复制代码
import pymysql

class Mysql(object):
    def __init__(self):
        try:
            # 打开数据库连接
            #连接数据库所需的值,可以在__init__()中传入
            self.conn = pymysql.connect(
                host = 'localhost',
                port = 3306,
                user = "root",
                passwd = 'root',
                db = "test",
                charset = 'utf8'
            )
        except Exception as e:
            print(e)
        else:
            print("connect successfully")
            # 使用 cursor() 方法创建一个游标对象 cursor
            self.cur = self.conn.cursor()

    def create_table(self):
        try:
            # 使用 execute() 方法执行 SQL,如果表存在则删除
            self.cur.execute("DROP TABLE IF EXISTS EMPLOYEE")
            # 使用预处理语句创建表
            sql = """CREATE TABLE EMPLOYEE (
                   FIRST_NAME  CHAR(20) NOT NULL,
                   LAST_NAME  CHAR(20),
                   AGE INT,  
                   SEX CHAR(1),
                   INCOME FLOAT )"""
            #执行sql语句
            self.cur.execute(sql)
            print("create table success")
        except Exception as e:
            print("create table error\n" + e)

    def add(self):
        #数据库插入语句
        sql = """insert into EMPLOYEE(First_Name,
                Last_Name,Age,Sex,Income) 
                values('Mac','Mohan',20,'F',2000);"""
        try:
            self.cur.execute(sql)
            # 提交到数据库执行
            self.conn.commit()
        except Exception as e:
            print(e)
            # 发生错误时回滚
            self.conn.rollback()
            print("fail to add new data")
        else:
            print("insert data seccess!")

    # Python查询Mysql使用
    # fetchone()方法获取单条数据, 使用fetchall()方法获取多条数据。
    # fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
    # fetchall(): 接收全部的返回结果行.
    # rowcount: 这是一个只读属性,并返回执行execute()
    # 方法后影响的行数。
    def show(self):
        sql = "select * from employee"
        try :
            self.cur.execute(sql)
            #fetchall()返回的结果是list,list里面再嵌套list
            res = self.cur.fetchall()
            for row in res:
                fname = row[0]
                lname = row[1]
                age = row[2]
                sex = row[3]
                income = row[4]

                # 打印结果
                print("\n fname =%s,lname =%s,age = %d, sex=%s,income=%d \n " % (fname, lname, age, sex, income))
        except  Exception as e:
            print(e + "select data fail")
        else:
            print("select data success")

    #更新数据库
    def upodate(self):
        sql = "update employee set age = age + 1 where sex ='%c'" %("m")
        try:
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            print(e)
        else:
            print("update data success")

    #删除数据库中数据
    def rem(self):
        sql = 'delete from employee where sex = "M"'
        try:
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            print(e)
        else:
            print("delete data success")

    #关闭数据库连接
    def close(self):
        self.cur.close()
        self.conn.close()
        print("close database success")



if __name__ == "__main__":
    mysql = Mysql()
    mysql.create_table()
    mysql.add()
    mysql.show()
    mysql.upodate()
    mysql.rem()
    mysql.close()
复制代码

可能会遇到的异常:

1.(1054, "Unknown column 'FirstName' in 'field list'")    在insert数据的时候遇到的,是因为字段没有创建

2.1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server

   version for the right syntax to use near '' at line 1"  可能是格式有问题

3.还有一些请参考http://www.runoob.com/python3/python3-mysql.html

 

本文作者:云龙

本文链接:https://www.cnblogs.com/yunlong-study/p/9243988.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   云long  阅读(1625)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开