简体   繁体   English

如何使用Python从Azure Databricks插入Azure SQL数据库

[英]How to INSERT INTO Azure SQL database from Azure Databricks in Python

Since pyodbc cannot be installed to Azure databricks, I am trying to use jdbc to insert data into Azure SQL database by Python, but I can find sample code for that. 由于无法将pyodbc安装到Azure数据块,因此我尝试使用jdbc通过Python将数据插入Azure SQL数据库,但是我可以找到该示例代码。

jdbcHostname = "xxxxxxx.database.windows.net"
jdbcDatabase = "yyyyyy"
jdbcPort = 1433
#jdbcUrl = "jdbc:sqlserver://{0}:{1};database={2};user={3};password={4}".format(jdbcHostname, jdbcPort, jdbcDatabase, username, password)

jdbcUrl = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbcHostname, jdbcPort, jdbcDatabase)
connectionProperties = {
  "user" : jdbcUsername,
  "password" : jdbcPassword,
  "driver" : "com.microsoft.sqlserver.jdbc.SQLServerDriver"
}

pushdown_query = "(INSERT INTO test (a, b) VALUES ('val_a', 'val_b')) insert_test" 

Please advise how to write insertion code in Python. 请告知如何用Python编写插入代码。 Thanks. 谢谢。

Since pyodbc cannot be installed to Azure databricks 由于无法将pyodbc安装到Azure数据块

Actually, it seems you could install pyodbc in databricks. 实际上,您似乎可以在databricks中安装pyodbc。

%sh    
apt-get -y install unixodbc-dev
/databricks/python/bin/pip install pyodbc

For more details, you could refer to this answer and this blog . 有关更多详细信息,您可以参考此答案和此博客

If I may add, you should also be able to use a Spark data frame to insert to Azure SQL. 如果可以添加的话,您还应该能够使用Spark数据框插入Azure SQL。 Just use the connection string you get from Azure SQL. 只需使用从Azure SQL获得的连接字符串即可。

connectionString = "<Azure SQL Connection string>"

data = spark.createDataFrame([(val_a, val_b)], ["a", "b"])

data.write.jdbc(connectionString, "<TableName>", mode="append")

Pigging backing on Jon ... This is what I used to write data from a Azure databricks dataframe to a Azure SQL Database: 支持Jon ...这是我用来将数据从Azure数据块数据帧写入Azure SQL数据库的方法:

    Hostname = "YOUR_SERVER.database.windows.net"
    Database = "YOUR_DB"
    port = 1433
    UN = 'YOUR_USERNAME'
    PW = 'YOUR_PASSWORD'
    Url = "jdbc:sqlserver://{0}:{1};database={2};user={3};password= {4}".format(Hostname, Port, Database, UN, PW)

   df.write.jdbc(Url, "schema.table", mode="append")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM