zoukankan      html  css  js  c++  java
  • Python

    基本用法

    # -*- coding: utf-8 -*-
    
    # !/usr/bin/python
    
    # 需要安装下面的驱动包
    import psycopg2
    
    # 连接到一个现有的数据库,如果数据库不存在,那么它就会被创建,最终将返回一个数据库对象。
    conn = psycopg2.connect(database="aoye", user="Chris", password="123456", host="127.0.0.1", port="5432")
    print("Opened database successfully")
    
    # 创建表:
    cur = conn.cursor()
    # cur.execute('''CREATE TABLE COMPANY
    #        (ID INT PRIMARY KEY     NOT NULL,
    #        NAME           TEXT    NOT NULL,
    #        AGE            INT     NOT NULL,
    #        ADDRESS        CHAR(50),
    #        SALARY         REAL);''')
    # print ("Table created successfully")
    
    # 插入数据
    # cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 
    #       VALUES (1, 'Paul', 32, 'California', 20000.00 )")
    #
    # cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 
    #       VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
    #
    # cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 
    #       VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
    #
    # cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) 
    #       VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
    # print("Records created successfully")
    
    # 查询数据
    cur.execute("SELECT id, name, address, salary  from COMPANY")
    rows = cur.fetchall()
    for row in rows:
       print("ID = ", row[0])
       print("NAME = ", row[1])
       print("ADDRESS = ", row[2])
       print("SALARY = ", row[3], "
    ")
    
    print("Operation done successfully")
    
    # 更新数据
    # cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
    
    # 删除数据
    # cur.execute("DELETE from COMPANY where ID=2;")
    conn.commit()
    conn.close()
    

    插入数据

    • 这里需要留意,插入的数据需要用如下方式传入(有些数据内容包含单引号,必须使用下面的方式插入)
    while True:
        url = f.readline().split()[1]
        if not url:
            break
        else:
            sql = """INSERT INTO urls(md5,url) VALUES (%s, %s)"""
            cur.execute(sql,(get_md5(url), url))
            conn.commit()
    

    参考文档:
    https://www.cnblogs.com/Erick-L/p/7106816.html

  • 相关阅读:
    《SQL Server 2008从入门到精通》--20180628
    2019国赛
    [蓝桥杯2020] 湖北省省赛
    2019第十届蓝桥杯B组决赛题解第五题
    试题 算法提高 分解质因数
    大数相加减
    试题 算法提高 汉诺塔
    试题 算法提高 欧拉函数
    试题 算法提高 天天向上-dp
    算法训练 猴子吃包子-构造
  • 原文地址:https://www.cnblogs.com/duchaoqun/p/11974812.html
Copyright © 2011-2022 走看看