from odps import ODPS
o = ODPS(
access_id='user', #登陆账号
secret_access_key='password', #登陆密码
project='project', #odps上的项目名称
endpoint='http://service.cn-hangzhou-xxx:80/api') #官方提供的接口
SQL:
1、查看表结构
with o.execute_sql('desc tablename').open_reader() as reader:
print(reader.raw)
2、查看表数据,直接将数据转为dataframe(有两种方式)
方法一:
# 直接使用 reader 的 to_pandas 方法
with o.execute_sql('select * from tablenamelimit 50').open_reader(tunnel=True) as reader:
# pd_df 类型为 pandas DataFrame
pd_df = reader.to_pandas()
print(pd_df)
【注】会碰到报错:ValueError: cannot find context for 'fork'
解决方法:更改to_pandas()方法的内容:
方法二:
table = o.get_table('tablename')
df = table.to_df()
print(df)
3、创建表
方法一:
create_sql = "create table if not tablename (" \
"id int comment '主键'," \
"name string comment '姓名'," \
"code string comment '编号'" \
")comment'表中文名';"
o.execute_sql(create_sql)
方法二:
table = o.create_table('my_new_table', schema='', if_not_exists=True) # 只有不存在表时才创建
4、删除表
o.delete_table('my_table_name', if_exists=True) # 只有表存在时删除
5、列出项目空间下的所有表,会列出每个表的表结构
for table in o.list_tables():
print(table)