zoukankan      html  css  js  c++  java
  • Python连接数据库

    #!/usr/bin/env python
    # coding:utf-8
    
    import sys
    # reload(sys)
    # sys.setdefaultencoding("utf-8")
    
    import pymysql
    import pymysql.cursors
    • 用phpadmin新建在mysql中新建自己的一个数据库,douban,然后新建一个表movie,当然也可以用代码建
    • 用Python连接数据库,然后用excute()方法想数据库中写入数据,数据库语言也就三种select updata delet
    • 用完数据库别忘了关闭,cursor.close() db.close()
    #!/usr/bin/env python
    # coding:utf-8
    
    import sys
    # reload(sys)
    # sys.setdefaultencoding("utf-8")
    
    import pymysql
    import pymysql.cursors
    
    db = pymysql.Connect(host='127.0.0.1', user='root', passwd='', db='douban', port=3306, charset='utf8')
    db.commit(True)
    cursor = db.cursor()
    
    # Create
    # 读取数据
    fr = open('../data/douban_movie_clean.txt', 'r',encoding="utf-8")
    print("----")
    
    count = 0
    
    for line in fr:
        try:
            count += 1
        # count表示当前处理到第几行了
            print (count)
            # 跳过表头
            if count == 1:
                continue
    
            # strip()函数可以去掉字符串两端的空白符
            # split()函数按照给定的分割符将字符串分割为列表
            line = line.strip().split('^')
            # 插入数据,注意对齐字段
            # execute()函数第一个参数为要执行的SQL命令
            # 这里用字符串格式化的方法生成一个模板
            # %s表示一个占位符
            # 第二个参数为需要格式化的参数,传入到模板中
            cursor.execute("insert into movie(title, url, rate, length, description) values(%s, %s, %s, %s, %s)", [line[1], line[2], line[4], line[-3], line[-1]])
        except Exception as e:
            print("error")
    
    
    # 关闭读文件
    fr.close()
    
    # Update
    # 更新需要提供条件、需要更新的字段、更新的新值
    # 以下对于id为1的记录,将其title和length两个字段进行更新
    cursor.execute("update movie set title=%s, length=%s where id=%s", ['全栈数据工程师养成攻略', 999, 1])
    
    # Read
    # 读取全部数据的全部字段
    cursor.execute("select * from movie")
    movies = cursor.fetchall()
    # 返回元组,每一项都是一个字典
    # 对应一条记录的全部字段和字段值
    print (type(movies), len(movies), movies[0])
    
    # 读取一条数据的部分字段
    # 返回一个字段,对应所选择的部分字段和字段值
    cursor.execute("select id, title, url from movie where id=2")
    movie = cursor.fetchone()
    print (type(movie), len(movie), movie)
    
    # # 读取一条数据的部分字段
    # # 按id降序排序,默认为升序
    cursor.execute("select id, title, url from movie order by id desc")
    movie = cursor.fetchone()
    print (type(movie), len(movie), movie)
    
    # # Delete
    # # 删除数据务必要提供删除条件
    # # 此处删除id为1的记录
    cursor.execute("delete from movie where id=%s", [1])
    
    # 关闭数据库连接
    cursor.close()
    db.close()
    

    大概流程,涉及到具体数据库更细粒度的操作,要再学习。

  • 相关阅读:
    LIBSVM使用介绍
    Symbian开发平台的搭建之VC++6.0&&Carbide C++ 2.0
    traits:Traits技术初探
    SDK与IDE的选择(附上设置默认SDK)
    浅析COM的思想及原理
    Windows Live Writer 支持的博客
    JQuery笔记(四) 通用选择的尝试
    JQuery笔记(一)
    JQuery笔记(二) animate支持的属性
    在DW绿化版或者精简版中使用扩展管理
  • 原文地址:https://www.cnblogs.com/caojunjie/p/8318888.html
Copyright © 2011-2022 走看看