zoukankan      html  css  js  c++  java
  • Python访问数据库

    Python访问数据库

    本文案例基于runoob数据库下,51job表演示

    image-20200917183446987

    1.MySQL的连接

    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect("localhost", "root", "123456", "runoob")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # 使用 execute() 方法执行 SQL,如果表存在则删除
    cursor.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 )"""
    
    cursor.execute(sql)
    
    # 关闭数据库连接
    db.close()
    

    2.插入数据

    from config import get_connect
    connect=get_connect('runoob')
    
    cursor=connect.cursor()
    
    # 执行SQl语句
    result=cursor.execute("insert into websites values (7,'秋弦','https://www.cnblogs.com/James-221',4,'China')")
    # 如果SQl语句是添加
    result=connect.commit()
    print('成功插入',cursor.rowcount,'条数据')
    

    image-20200917183642816

    image-20200917183724053

    3.修改数据

    from config import get_connect
    connect=get_connect('runoob')
    
    cursor=connect.cursor()
    
    # 执行SQl语句
    result=cursor.execute("update websites set alexa=2 where id=1")
    # 如果SQl语句是添加
    connect.commit()
    print('成功修改',cursor.rowcount,'条数据')
    

    image-20200917183857195

    image-20200917183913814

    4.删除数据

    from config import get_connect
    connect=get_connect('runoob')
    
    cursor=connect.cursor()
    
    # 执行SQl语句
    result=cursor.execute("delete from websites where id=7")
    # 如果SQl语句是添加
    connect.commit()
    print('成功删除',cursor.rowcount,'条数据')
    

    image-20200917184005557

    image-20200917184025078

    5.查询数据

    from config import get_connect
    connect=get_connect('runoob')
    
    cursor=connect.cursor()
    
    # 执行SQl语句
    result=cursor.execute("select * from websites")
    # 如果SQl语句是添加
    result=connect.commit()
    for row in cursor.fetchall():
        print(row)
    print('共查出',cursor.rowcount,'条数据')
    

    image-20200917184045853

    6.基本操作

    import pymysql
    from config import get_connect
    connect=get_connect('job')
    print('数据库连接成功')
    
    # 获取游标对象,游标对象可以将SQL语句发送到mysql数据库并执行
    cursor=connect.cursor()
    # 执行SQl语句
    result=cursor.execute('select * from 51job')
    
    # print(type(result))
    # print(result)
    
    # 从游标对象中获取一条数据
    # data=cursor.fetchone()
    # print(data)
    
    # 从游标对象中获取10条数据
    # data=cursor.fetchmany(10)
    # for row in data:
    #     print(row)
    
    # 获取所有数据
    # data=cursor.fetchall()
    # print(len(data))
    
    # 数据库连接结束后,关闭游标和连接
    cursor.closo()
    connect.close()
    

    案例:

    题目需求:

    文件操作+数据库练习

    1)使用pymsql创建数据库和数据表,库名称:test,表名称:51job2)使用任意可用与解析excel文件的模块,解析51job.xls
    3)使用pymysql将51job.xls中的数据添加到test.5ljob表中
    4)使用pymysql查询test.51job中的所有数据,筛选出位于”上海-浦东新区”的所有工作岗位

    1.创建一个配置文件config.py

    import pymysql
    HOST='localhost'
    USER='root'
    PWD='123456'
    
    def get_connect(db):
        connect=pymysql.connect(host=HOST,
                                user=USER,
                                password=PWD,
                                db=db)
        return connect
    

    2.demo.py

    # 读取F:\Python资料\51job.xls文件内容后,将需要到字段信息(jobName,company,location,salary,postDate)存入mysql数据库实例,最终记得要关数据库和连接哦!
    # 读取excel表的内容然后写入数据库
    import xlrd,pymysql
    from config import get_connect
    # 连接的数据库
    conn = get_connect('runoob')
    def insert():
    # 获取游标对象
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        sql = "insert into 51job (jobName,company,location,salary,postDate) values (%s,%s,%s,%s,%s)"
        # 打开文件
        file = xlrd.open_workbook("F:\Python资料\51job.xls")
        sheet_1 = file.sheet_by_index(0) # 根据sheet页的排序选取sheet
        row_content = sheet_1.row_values(0) # 获取指定行的数据,返回列表,排序自0开始
        row_number = sheet_1.nrows # 获取有数据的最大行数
    # 从第一行开始遍历
        for i in range(1,row_number):
        #
            jobName = sheet_1.cell(i,0).value
            company = sheet_1.cell(i,1).value
            location = sheet_1.cell(i,2).value
            salary = sheet_1.cell(i,3).value
            postDate = sheet_1.cell(i,4).value
            values = (jobName,company,location,salary,postDate)
        # 执行sql语句插入数据
            cursor.execute(sql,values)
            conn.commit()
    
        # 关必游标
        cursor.close()
        # 关闭连接
        conn.close()
    insert()
    
    # 查询地址在上海-浦东新区的数据
    def select():
        connect = get_connect('runoob')
        cursor = connect.cursor()
        # 执行SQl语句
        result = cursor.execute("select * from 51job where location like '%上海-浦东新区'")
        # 如果SQl语句是添加
        result = connect.commit()
        for row in cursor.fetchall():
            print(row)
        print('共查出', cursor.rowcount, '条数据')
    select()
    

    image-20200917182301606

  • 相关阅读:
    正则化--Lambda
    uwsgi配置cheaper模式进行自动弹性
    采集容器内存并写到excel
    通过进程id找到进程对应的容器并统计每个进程的内存占用写到excel里
    基于celery的任务管理
    基于Redis做内存管理
    uWSGI
    nginx
    服务发现
    绑核与巨页
  • 原文地址:https://www.cnblogs.com/James-221/p/13686819.html
Copyright © 2011-2022 走看看