Integration of Python with Julia

Hi, I want to access data base with Python and want to transfer value retrieved by Python to Julia. Code is very common and available on internet. Pls check it is mentioned below:

import pyodbc
import DBConfig
import numpy as np
#string connection ="Data Source=KRISHNA\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True"
def dbconn():
    cnxn = pyodbc.connect(DBConfig.DBConnectString)
    cursor = cnxn.cursor()

    cursor.execute("SELECT * FROM BOM")
    rows = cursor.fetchall()

    bomid=np.empty(len(rows),dtype=object)
    i=0
    for row in rows:
      
       bomid[i]=row.BOMID
       i+=1
    return bomid

Calling Python from Julia

module Test
export TestDB
BOMID=Dict()
julia_script_path="............/Julia/"
ENV["PYTHONPATH"]="............../Python/"
using PyCall
@pyimport pyodbc
@pyimport DBConnect
function TestDB()

BOMID=DBConnect.dbconn()
#for i=1:length(BOMID)
#  println(string("BOM ID:",BOMID[i]))
#end
return BOMID
end
end

Code is working. But only problem is BOMID is taking the value

PyCall.PyObject[PyObject Decimal('1234'),PyObject Decimal('1235')]

How to take only “1234” or :“1235”??

Good question. In Python, you would call str on a Decimal object to get it in string form. I just noticed that PyCall wasn’t exporting any equivalent of this, so I added a pystr function.

If you checkout the latest PyCall master (Pkg.checkout("PyCall")), you can do pystr.(BOMID) to convert each object to a string.

2 Likes

Please show me the code of pystr function

If you are running Julia with PyCall, you can do @which pystr(PyObject(1)) to see where the code is, or use @edit to open it in an editor. You can also just search for “pystr” in the PyCall github repository. In either case, you’ll quickly see that it is just a call to PyObject_Str in the C API, which is equivalent to str in Python.

4 Likes