安装指南 — PyODPS 0.10.7.1 文档

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)

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐