【问题标题】:Connect to SQLite3 server using PyODBC, Python使用 PyODBC、Python 连接到 SQLite3 服务器
【发布时间】:2015-07-01 14:45:17
【问题描述】:

我正在尝试测试一个从给定查询的 SQL 服务器加载数据的类。为此,我被指示使用sqlite3。现在,问题是,虽然该类设法轻松连接到真实数据库,但我正在努力连接我创建的临时sqlite3 服务器,因为我无法弄清楚连接字符串应该是什么样子。我在课堂上使用pyodbc 来连接数据库。那么,有人知道连接字符串应该是什么样子吗?

类如下所示:

import petl as etl
import pyodbc
class Loader:
  """
  This is a class from which one can load data from an SQL server.
  """

  def __init__(self, connection_string):
      """
      This is the initialization file, and it requires the connection_string.

      :param connection_string:
      :type connection_string: str
      :return:
      """

      self.connection = pyodbc.connect(connection_string)

  def loadFromSQL(self, query):
      """
      This function loads the data according to the query passed in query.

      :param query:
      :type query: str
      """

      self.originalTableETL = etl.fromdb(self.connection, query)

      self.originalTablePD = etl.todataframe(self.originalTableETL)

而临时的sqlite3服务器如下

import sqlite3 as lite
con = lite.connect('test.db')
with con:
  cur = con.cursor()
  cur.execute("DROP TABLE IF EXISTS test_table")
  cur.execute("CREATE TABLE test_table(col1 TEXT, col2 TEXT)")
  cur.execute("INSERT INTO test_table VALUES('Hello', 'world!')")

所以,我想输入的是类似的东西

tester = Loader('connection_string_goes_here')
tester.loadFromSQL("SELECT * FROM test_table")

编辑

好的,我在网上搜索了一下,发现可能的连接字符串是 "DRIVER={SQL Server};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"。但是,一段时间后连接超时并返回以下错误消息:

pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect)')

我觉得很奇怪,因为它是本地的,而且我没有指定任何密码。我也尝试过指定确切的路径名,但无济于事。

最好的,

维克多

【问题讨论】:

  • 您能否发布有关您创建的 sqlite 服务器的更多详细信息?到目前为止,您拥有的现有代码是什么?还可以在此处找到许多字符串外观的示例:code.google.com/p/pyodbc/wiki/GettingStarted
  • 当然,我会编辑!
  • 您正在使用众多 SQLite ODBC 驱动程序中的哪一种?
  • 我目前正在使用sqlite3pyodbc

标签: python sql sqlite


【解决方案1】:

解决了问题!从http://www.ch-werner.de/sqliteodbc/下载了SQLite的ODBC驱动,并定义了连接字符串如

"DRIVER={SQLite3 ODBC Driver};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"

成功了,希望对大家有所帮助!

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多