Python从SAP获取数据

本文介绍如何利用Python编程语言连接到SAP系统,并详细阐述了从SAP获取数据的过程,适合对Python和SAP集成感兴趣的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from pyrfc import Connection
import re

class main():
def __init__(self):
ASHOST='sapxxxxx'
CLIENT='x00'
SYSNR='00'
USER='XXXXXXXX'
PASSWD='XXXXXXXX'
self.conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)

def qry(self, Fields, SQLTable, Where = '', MaxRows=50, FromRow=0):
"""A function to query SAP with RFC_READ_TABLE"""

# By default, if you send a blank value for fields, you get all of them
# Therefore, we add a select all option, to better mimic SQL.
if Fields[0] == '*':
Fields = ''
else:
Fields = [{'FIELDNAME':x} for x in Fields] # Notice the format

# the WHERE part of the query is called "options"
options = [{'TEXT': x} for x in Where] # again, notice the format

# we set a maximum number of rows to return, because it's easy to do and
# greatly speeds up testing queries.
rowcount = MaxRows

# Here is the call to SAP's RFC_READ_TABLE
tables = self.conn.call("RFC_READ_TABLE", QUERY_TABLE=SQLTable, DELIMITER='|', FIELDS = Fields, \
OPTIONS=options, ROWCOUNT = MaxRows, ROWSKIPS=FromRow)

# We split out fields and fields_name to hold the data and the column names
fields = []
fields_name = []

data_fields = tables["DATA"] # pull the data part of the result set
data_names = tables["FIELDS"] # pull the field name part of the result set

headers = [x['FIELDNAME'] for x in data_names] # headers extraction
long_fields = len(data_fields) # data extraction
long_names = len(data_names) # full headers extraction if you want it

# now parse the data fields into a list
for line in range(0, long_fields):
fields.append(data_fields[line]["WA"].strip())

# for each line, split the list by the '|' separator
fields = [x.strip().split('|') for x in fields ]

# return the 2D list and the headers
return fields, headers

# Init the class and connect
# I find this can be very slow to do...
s = main()

# Choose your fields and table
fields = ['MATNR', 'EAN11']
table = 'MEAN'
# you need to put a where condition in there... could be anything
where = ['MATNR <> 0']

# max number of rows to return
maxrows = 10

# starting row to return
fromrow = 0
# Pretty Printer
pp = PrettyPrinter(indent=1)
# query SAP
results, headers = s.qry(fields, table, where, maxrows, fromrow)

print(headers)
pp.pprint(results)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SAP扫地僧

你的鼓励将是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值