PostgreSQL初学

SQL语句

  1. 创建数据库

    create database tyk;

    显示所有数据库: \l;

    切换数据库: \c +name;

    显示该数据库的所有表: \d +tablename;

  2. 导入数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    create table data(
    update_time date,
    id text,
    title text,
    price numeric,
    sale_count int,
    comment_count int,
    店名 text
    );
    \copy data from 'G:\PostgreSQLData\数据可视化微专业_体验课资料\美妆数据.csv' with csv header;
  3. 查看数据

    1
    2
    3
    select * from data;
    select id, title, price from data limit 10;
    select * from data where id is null limit 10;
  4. 删除数据

    1
    delete from data where sale_count is null;

    例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
create table OD2Array(
cardid text,
car_num text,
line text,
upsta text,
uptime date,
downsta text,
downtime date,
pi numeric,
a text
);
create table indexS(
lineName text,
mer1 text,
labelsta int
);
-- 连接语句

psycopg2库

1
2
3
conn = pg.connect(database, user, password, host, port)
conn.commit()
conn.close() # Python操作PostgreSQL,只有当连接关闭时,程序对数据库的操作才会生效(close之前必须要commit)

cursor对象

1
2
3
4
5
cur = conn.cursor() # 创建cursor
cur.execute(SQL) # 执行sql
cur.fetchall() # 提取查询结果集的所有行
cur.fetchone() # 提取查询结果集的下一行
cur.fetchmany()