使用Python通过Java连接BigSQL

时间:2017-05-04 14:33:13

标签: java python bigsql

我正在尝试将python连接到BigSQL。我有一个java代码可以将python连接到BigSQL&从BigSQL中检索数据.Below是我的示例代码

 public class Hello {

  public static void main(String[] args) {
    try(Connection con = DriverManager.getConnection("connection details")) {

Class.forName("com.ibm.db2.jcc.DB2Driver");
    Statement stmt = con.createStatement();
    System.out.println("Connected to BigSQL");      
    ResultSet result = stmt.executeQuery("select *  from table limit 10");
    while (result.next()) {
      //Retrieve by com_name
      String com_name = result.getString(1);
      //Retrieve by family
      String family = result.getString(2); 
      //Retrieve by sci_name
      String sci_name = result.getString(3);
      //Retrieve by symbol
      String symbol = result.getString(4);
      //Retrieve by synonym
      String synonym = result.getString(5);
     System.out.println(com_name+":"+family+":"+sci_name+":"+symbol+":"+synonym);
    }

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }

}  

我写了一个python代码,用我的python

调用这个java代码
import os
import os.path,subprocess
from subprocess import STDOUT,PIPE
path='Location where my .java file is'
os.chdir(path)
def compile_java(java_file):
    subprocess.check_call(['javac', java_file])


def execute_java(java_file):
    java_class,ext = os.path.splitext(java_file)
    cmd = ['java', java_class]

compile_java('Hello.java')      
execute_java("Hello")

我的python代码运行成功,但我无法检索

中提到的java输出
System.out.println(com_name+":"+family+":"+sci_name+":"+symbol+":"+synonym);

你能帮帮我吗?

先谢谢

1 个答案:

答案 0 :(得分:0)

您需要执行对java的调用并使用check_output来获取java输出。 check_call只返回返回码:

def execute_java(java_file):
    java_class,ext = os.path.splitext(java_file)
    cmd = ['java', java_class]
    print(cmd)
    javaStdout =subprocess.check_output(['java', java_class])
    print ('>>', javaStdout)

execute_java("HelloWorld")

回报:

['java', 'HelloWorld']
>> b'Hello World!\n'