2015-06-15 85 views
1

我讀過從Python ODBC庫以及其他實例中,所有的問題網頁,併成功地連接到DSN,使用下面的代碼連接到ODBC:使用pyODBC

cnxn = pyodbc.connect("DSN=DSNNAME") 
cursor = cnxn.cursor() 
cursor.tables() 
rows = cursor.fetchall() 
for row in rows: 
    print row.table_name 

但一切我不斷收到此錯誤:

Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') 

我知道,我可以通過以下步驟要使用Microsoft Access拉起我的數據:創建一個新的數據庫,單擊外部數據選項卡,單擊更多,然後選擇ODBC數據庫,通過在Sele中創建鏈接表來使用鏈接到數據源ct數據源窗口選擇機器數據源並選擇具有系統類型的NAME2,按好,然後選擇表格acr.Table_one_hh,然後選擇表格中我想查看的字段,如城市,州,國家,地區等。當我將鼠標懸停在表名上時,它顯示DSN名稱,描述,可信連接=是,APP,數據庫名稱和表名。

我已經嘗試了兩種方法,第一

cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=mycomputername;DATABASE=mydatabase;Trusted_Connection=yes;') 
cursor = cnxn.cursor() 

它給出了一個錯誤:

Error: ('08001', '[08001] [Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect); [HYT00] [Microsoft][SQL Server Native Client 10.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (2)') 

我試圖

cnxn = pyodbc.connect("DSN=DSNNAME, DATABASE=mydatabase") 
cursor = cnxn.cursor() 
cursor.execute("""SELECT 1 AS "test column1" from acr.Table_one_hh""") 
cursor.tables() 
rows = cursor.fetchall() 
for row in rows: 
    print row.table_name 

這給了一個錯誤

Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') 
+1

您的最後一個示例不正確,因爲連接字符串屬性的分隔符是分號(';'),而不是逗號(',')。試試'DSN = DSNNAME; DATABASE = mydatabase'。 –

回答

1

我設法解決了我的問題。我的代碼並沒有真正改變。

cnxn = pyodbc.connect("DSN=BCTHEAT") 
cursor = cnxn.cursor() 
cursor.execute("select * from acr.Table_one_hh") 
row = cursor.fetchall() 

然後我把結果寫到一個csv文件中。