如何使用pymssql / python检索多个SQL结果集

时间:2018-04-04 12:24:50

标签: java python sql pymssql

我想调用的存储过程返回多个返回结果集,而不是通常的1个结果集表。我需要执行该存储过程并使用pymssql通过python检索它的结果。

在Java中,这可以通过扩展org.springframework.jdbc.object.StoredProcedure,提供多个SqlReturnResultSet并调用.execute .execute(params)返回Map<String, Object>来实现,您可以通过String访问每个返回的结果集最初在SqlReturnResultSet中提供的import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.SqlReturnResultSet; import org.springframework.jdbc.object.StoredProcedure; import org.springframework.dao.DataAccessException; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyStoredProcedure extends StoredProcedure { public GetMultiple() { final SqlParameter[] sqlResultParameters = new SqlParameter[] { new SqlReturnResultSet("returnResultSet1", new RowMapper()), new SqlReturnResultSet("returnResultSet2", new RowMapper()) }; declareParameter(sqlResultParameters) final Map<String, Object> spResult = super.execute(); spResult.getOrDefault("returnResultSet1", Collections.emptyList()) spResult.getOrDefault("returnResultSet2", Collections.emptyList()) } } 密钥:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 60)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, view.frame.size.width-20, 60)];
[label setFont:[UIFont boldSystemFontOfSize:18]];
NSString *string =@"FAQ//....your label text";
[label setText:string];
label.textColor=[UIColor blackColor];
label.numberOfLines=0;
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[view addSubview:label];
[view setBackgroundColor:[UIColor whiteColor]];//set which color you want
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 60;
}

如何在Python中完成此操作?

1 个答案:

答案 0 :(得分:2)

Python不会自动映射结果集,而是会创建缓冲游标,但您可以使用cursor.nextset()迭代它们,例如:

connection = pymysql.connect(host="host", user="user", password="pass", db="schema")  # etc.

with connection.cursor() as cursor:
    cursor.callproc("procedure_name", ("foo", "bar"))  # pass procedure parameters as a tuple
    while True:  # loop while there are result sets
        if cursor.rowcount:  # make sure there are actually results in the current set
            result_set = cursor.fetchall()  # or cursor.fetchone() / cursor.fetchmany()
            # do whatever you want with the result_set, store it in a dict if you want
        # after done processing the current result set, move on to the next
        if not cursor.nextset():  # switch to the next result set, if available...
            break  # exit the loop if not