美文网首页Pyhton
Python操作MySQL数据库

Python操作MySQL数据库

作者: HeloWxl | 来源:发表于2019-10-20 02:36 被阅读0次

数据库

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

Python连接数据库

# 连接
conn = pymysql.connect(host="localhost", user="root", password="123456", database="book", charset="utf8")
# 获取光标
cursor = conn.cursor()

获取数据库版本信息

def getMysqlVersion():
    # 执行一个查询
    cursor.execute("SELECT VERSION()")
    # 取得上个查询的结果,是单个结果
    data = cursor.fetchone()
    print("Database version : '%s' "% data )

#添加数据同时获取刚刚插入数据的ID

def insertBook(name,price):
    sql = '''insert book (name,price) values ('%s','%d')'''%(name,price)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交
        conn.commit()
        print("添加成功")
        last_id = cursor.lastrowid
        print('--->刚才插入的那条数据的id值是:', last_id)
    except Exception as e:
        print("添加失败")
        # 捕捉到错误就回滚
        conn.rollback()

修改

# 修改
def updateBook(name,price,id):
    sql = '''update book set name = '%s' ,price = '%d' where id = '%d' ''' % (name,price,id)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交
        conn.commit()
        print("修改成功")
    except Exception as e:
        print("修改失败")
        # 捕捉到错误就回滚
        conn.rollback()

根据ID查询

# 根据ID查询
def getBookById(id):
    sql = '''select * from book where id = '%d' '''%(id)
    ret = cursor.execute(sql)
    print("得到结果的数量:"+str(ret))
    # 取出所有的数据
    print(cursor.fetchall())
'''
    得到结果的数量:1
    ((2, 'math', 23),)
'''

查询所有的数据

# 查询所有的数据
def getAllBook():
    sql = '''select * from book '''
    ret = cursor.execute(sql)
    print("得到结果的数量:" + str(ret))
    # 只取出一条数据
    print(cursor.fetchone())
    # 取出剩下所有的数据
    print(cursor.fetchall())
    # 当全部取出完后,再取出一条的话 ,取出的内容就是None
    print(cursor.fetchone())

'''
    得到结果的数量:5
    (1, '高等数学', 212)
    ((2, 'math', 23), (3, 'chinese', 22), (4, 'english', 32), (5, '数学', 20))
    None
'''

根据ID删除数据

# 根据ID删除数据
def deleteBookById(id):
    sql = ''' delete from book where id = '%d' '''%(id)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交
        conn.commit()
        print("删除成功")
    except Exception as e:
        print("删除失败")
        # 捕捉到错误就回滚
        conn.rollback()
'''
删除成功
'''

相关文章

网友评论

    本文标题:Python操作MySQL数据库

    本文链接:https://www.haomeiwen.com/subject/hnromctx.html