如果您想知道如何使用 JMP 的嵌入式 Python 環境導入資料庫,這裡有一些範例可以幫助您入門。在第一個範例中,我使用 pyodbc 模組從 SQL Server 資料庫匯入資料;我在第二個範例中使用 OracleDB 模組。如果您熟悉 SQL 和 Python,並且需要在不離開 JMP 的情況下快速執行 SQL,我想您會喜歡這些快速提示。
注意:您可以將 pyodbc 與多種資料庫管理系統(MySQL、SQL Server、PostgreSQL 等)一起使用。 Oracledb只能用於建立Oracle資料庫連線。
先決條件:
範例 1:使用 Python 模組 pyodbc
#Imports the jmp modules jmp. Pandas and jmputils.
import jmp
import jmputils
import pandas as pd
#Installs pyodbc andpandas if they have not been installed before.
#jmputils.jpip('install', 'pyodbc pandas')
#import the module pyodbc.
import pyodbc
#Defines variables for the driver's ODBC parameters.
drv = ''
db = ''
server = ''
uid = ''
pw = ''
#Passes the defined variables to the connection string parameters and establishes a connection.
cnxn = pyodbc.connect('DRIVER={%s};Server=%s;Database=%s;uid=%s;pwd=%s' % (drv, server, db, uid, pw))
#Defines a variable for the SQL query.
query = 'SELECT * FROM dbo.tablename'
#Executes the SQL query and prints the DataFrame df.
cursor = cnxn.cursor()
df = pd.read_sql(query, con=cnxn)
print (df)
cnxn.close()
#Run jmp.run_JSL to get the DataFrame 'df'.
jmp.run_jsl('python get (df)<< newdataview;'
);
範例 2:使用 Python 模組 Oracledb
#Imports the jmp modules jmp and jmputils.
import jmp
import jmputils
import pandas as pd
#Installs oracledb and pandas if they have not been installed before.
#jmputils.jpip('install', 'oracledb pandas')
#Imports the module oracledb.
import oracledb
#Passes the connection string parameters to the database to establish a connection.
con = oracledb.connect(user='', password='', service_name='', host='', port='')
#Executes the SQL query and prints it as the list 'res'.
cur = con.cursor()
cur.execute('SELECT * FROM dbo.tablename')
res = cur.fetchall()
for row in res:
print(row)
#Converts the list 'res' to a pandas DataFrame.
df_ora = pd.DataFrame(res)
print(df_ora)
#Runs jmp.run_JSL to get the DataFrame 'df_ora'.
jmp.run_jsl('python get ("df_ora") << newdataview;')