Ari*_*ick 3 sql odbc function julia
我正在编写一个查询 SQL 数据库的函数,但遇到了一个 ReadOnlyMemoryError() ,这让我很困惑。问题是,当我将代码作为简单脚本运行时,一切都会按预期运行。但是当我尝试将完全相同的代码包装在函数中时,我得到了 ReadOnlyMemoryError()。
这是我的代码的脚本版本:
using ODBC
using DBInterface
using Dates
using DataFrames
server = "server string "
username = "username "
password = " password"
db = " db name"
start_date=Nothing
end_date=Nothing
if start_date == Nothing || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if end_date == Nothing || typeof(end_date) != "Date"
end_date = Dates.today()
end
query = """ SQL SELECT statement """
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
df = DBInterface.execute(conn, query) |> DataFrame
Run Code Online (Sandbox Code Playgroud)
这按预期工作,结果是一个大约 500k 行的数据帧 df。但是,当我尝试使用相同的代码来创建可重用函数时,我收到错误:
using ODBC
using DBInterface
using Dates
using DataFrames
function get_cf_data(start_date=Nothing, end_date=Nothing)
server = " server string "
username = " user name"
password = " password"
db = " db "
if start_date == Nothing || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if end_date == Nothing || typeof(end_date) != "Date"
end_date = Dates.today()
end
query = """ SQL SELECT statement """
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
df = DBInterface.execute(conn, query) |> DataFrame
return df
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当我尝试从 REPL get_cf_data() 调用时,我收到错误:ReadOnlyMemoryError()。我对 Julia 有点陌生,所以任何见解都将非常感激。谢谢你!
正如所评论的,大多数编程语言在集成 ODBC 连接等 API 时的最佳实践是在使用后关闭并释放其资源。
此外,请考虑参数化(运行传递文字值的 SQL 的任何语言的最佳实践),在其中设置准备好的 SQL 语句并在后续调用中绑定值execute。
function get_cf_data(start_date=Nothing, end_date=Nothing)
server = " server string "
username = " user name"
password = " password"
db = " db "
if isnothing(start_date) || typeof(start_date) != "Date"
start_date = Dates.today() - Dates.Day(30)
end
if isnothing(end_date) || typeof(end_date) != "Date"
end_date = Dates.today()
end
# PREPARED STATEMENT WITH QMARK PLACEHOLDERS
sql = """SELECT Col1, Col2, Col3, ...
FROM myTable
WHERE myDate BETWEEN ? AND ?
"""
connect_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" * server *
";DATABASE=" * db *
";UID=" * username *
";PWD=" * password
conn = ODBC.Connection(connect_string)
# PREPARE STATEMENT AND BIND PARAMS
stmt = DBInterface.prepare(conn, sql)
df = DBInterface.execute(stmt, (start_date, end_date)) |> DataFrame
DBInterface.close(stmt) # CLOSE STATEMENT
DBInterface.close(conn) # CLOSE CONNECTION
stmt = Nothing; conn = Nothing # UNINTIALIZE OBJECTS
return df
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |