亲宝软件园·资讯

展开

Python 操作MySQL

​ 孤寒者   ​ 人气:0

文章介绍内容:

操作MySQL数据库:

面试题:

一、创建MySQL数据表

# coding=utf-8
from pymysql import *
def connectDB():
    '''
    连接本地MySQL数据库,指定连接的库为test库。
    :return:
    '''
    db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
    return db
db = connectDB()
print(type(db))
def createTable(db):
    c = db.cursor()
    try:
        c.execute('''create table persons
                    (id int primary key not null,
                    name text not null,
                    age int not null,
                    address char(100),
                    salary real);''')
        db.commit()
        db.commit()
        return True
    except:
        db.rollback()
    return False
if createTable(db):
    print('create table success')
else:
    print('create table failed')

使用navicat工具查看: 

三、向MySQL表中插入数据

# coding=utf-8
from pymysql import *
def connectDB():
    '''
    连接本地MySQL数据库,指定连接的库为test库。
    :return:
    '''
    db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
    return db
db = connectDB()
print(type(db))
def insertRecords(db):
    cursor = db.cursor()
    try:
        cursor.execute("delete from persons")
        cursor.execute('''
        insert into persons(id,name,age,address,salary)
        values(1, 'GuHanZhe', 18, 'China', 9999)
        ''')
        cursor.execute('''
        insert into persons(id,name,age,address,salary)
        values(2, 'XiaoZhang', 55, 'China', 9)
        ''')
        db.commit()
        return True
    except Exception as e:
        print(e)
        db.rollback()
    return False
if insertRecords(db):
    print("成功插入记录")
else:
    print("插入记录失败")

使用navicat工具查看:

三、查询MySQL中的数据

# coding=utf-8
from pymysql import *
def connectDB():
    '''
    连接本地MySQL数据库,指定连接的库为test库。
    :return:
    '''
    db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
    return db
db = connectDB()


def selectRecords(db):
    cursor = db.cursor()
    sql = 'select name,age,salary from persons order by age desc'
    cursor.execute(sql)
    results = cursor.fetchall()
    print(results)
    print(type(results))    # 打印发现是元组类型

selectRecords(db)
db.close()

# coding=utf-8
import json
from pymysql import *
def connectDB():
    '''
    连接本地MySQL数据库,指定连接的库为test库。
    :return:
    '''
    db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
    return db
db = connectDB()


def selectRecords(db):
    cursor = db.cursor()
    sql = 'select name,age,salary from persons order by age desc'
    cursor.execute(sql)
    results = cursor.fetchall()
    print(results)
    print(type(results))    # 打印发现是元组类型

    # 将字段名和查询结果整合在一起
    fields = ['name', 'age', 'salary']
    records = []
    for row in results:
        records.append(dict(zip(fields, row)))
    return json.dumps(records)      # 输出类型为JSON字符串
endresults = selectRecords(db)
print(endresults)
db.close()

总结

注意:我们使用的是pymysql模块中的API来操作MySQL数据库,该模块需要单独安装

加载全部内容

相关教程
猜你喜欢
用户评论