将Python与SQL Server数据库连接

时间:2017-02-24 07:56:33

标签: python sql-server

当我尝试将python与SQL Server连接时,发生以下错误。

  

“pyodbc.Error:('08001','[08001] [Microsoft] [ODBC SQL Server   驱动程序] [DBNETLIB] SQL Server不存在或访问被拒绝。 (17)   (的SQLDriverConnect)')“

以下是我的代码。

import pyodbc
connection = pyodbc.connect("Driver={SQL Server}; Server=localhost;          
Database=emotionDetection; uid=uname ;pwd=pw;Trusted_Connection=yes")
cursor = connection.cursor()
SQLCommand = ("INSERT INTO emotion"  "(happy, sad, angry) "
          "VALUES (?,?,?)")
Values = ['smile','cry','blame']
cursor.execute(SQLCommand,Values)
connection.commit()
connection.close()

这是我第一次尝试连接 Python与sql server 。我不知道驱动程序名称,服务器名称,用户名和密码是什么。你知道我的配置应该是什么。请帮帮我。

5 个答案:

答案 0 :(得分:2)

我想你应该看看这个。 stackoverflow answer about odbc

另外,你使用什么sql server?

答案 1 :(得分:0)

工作示例最适合我:

需要Mac ODBC驱动程序吗?

如果需要Mac驱动程序,我使用了homebrewfound the commands here

详细信息

我个人通过反向工程学得最好,这就是说我分享了我的一个例子,这可能有点粗糙,但是我正在提高我的Python技能。

My script I created允许我将Mac OS连接到AWS RDS实例。

整个脚本是一个复制粘贴,对您的服务器信息进行了一些修改,然后就可以运行了。 只需修改这些线路即可连接。

server = 'yourusername'
username = 'yourusername'
password = 'yourforgottencomplicatedpassword'
database = 'yourdatabase'

然后运行文件:python3 ~/Your/path/pyodbc_mssqldbtest.py,您应该被设置。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By  : Jeromie Kirchoff
# Created Date: Mon July 31 22:32:00 PDT 2018
# FILENAME: pyodbc_mssqldbtest.py
# =============================================================================
"""The Module Has Been Build for Interaction with MSSQL DBs To Test the con."""
# =============================================================================
# Thanks to this post for headers https://stackoverflow.com/q/12704305/1896134
# Answer to an SO question: https://stackoverflow.com/q/42433408/1896134
# =============================================================================

import pyodbc


def runningwithqueries(query):
    """The Module Has Been Build to {Open, Run & Close} query connection."""
    print("\nRunning Query: " + str(query) + "\nResult :\n")
    crsr = cnxn.execute(query)
    columns = [column[0] for column in crsr.description]
    print(columns)
    for row in crsr.fetchall():
        print(row)
    crsr.close()

# =============================================================================
# SET VARIABLES NEEDED FOR SERVER CONNECTION
# =============================================================================
server = 'yourusername'
username = 'yourusername'
password = 'yourforgottencomplicatedpassword'
database = 'yourdatabase'

connStr = (r'DRIVER={ODBC Driver 17 for SQL Server};' +
           r"Integrated Security=True;" +
           r'SERVER=' + server +
           r';UID=' + username +
           r';PWD=' + password +
           r';DSN=MSSQL-PYTHON' +
           r';DATABASE=' + database + ';'
           )

print("Your Connection String:\n" + str(connStr) + "\n\n")

# =============================================================================
# CONNECT TO THE DB
# =============================================================================
cnxn = pyodbc.connect(connStr, autocommit=True)

# =============================================================================
# SET QUERIES TO VARIABLES
# =============================================================================
SQLQUERY1 = ("SELECT @@VERSION;")
SQLQUERY2 = ("SELECT * FROM sys.schemas;")
SQLQUERY3 = ("SELECT * FROM INFORMATION_SCHEMA.TABLES;")
SQLQUERY4 = ("SELECT * FROM INFORMATION_SCHEMA.COLUMNS;")
SQLQUERY5 = ("SELECT * FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS;")
SQLQUERY6 = ("EXEC sp_databases;")
SQLQUERY7 = ("EXEC sp_who2 'active';")

# =============================================================================
# RUN QUERIES
# YOU CAN RUN AS MANY QUERIES AS LONG AS THE CONNECTION IS OPEN TO THE DB
# =============================================================================
runningwithqueries(SQLQUERY1)
runningwithqueries(SQLQUERY2)
runningwithqueries(SQLQUERY3)
runningwithqueries(SQLQUERY4)
runningwithqueries(SQLQUERY5)
runningwithqueries(SQLQUERY6)
runningwithqueries(SQLQUERY7)

# =============================================================================
# CLOSE THE CONNECTION TO THE DB
# =============================================================================
cnxn.close()

答案 2 :(得分:0)

pymssql库不需要任何驱动程序,并且可以在Windows和Ubunutu上运行。

import pymssql
import pandas as pd

server = 'yourusername'
username = 'yourusername'
password = 'yourpassword'
database = 'yourdatabase'
table_name = 'yourtablename'
conn = pymssql.connect(host=server,user=username,password=password,database=database)
dat = pd.read_sql("select * from table_name,conn)

答案 3 :(得分:0)

尝试使用SQLalchemy的pyodbc

尝试一下:

import sqlalchemy
import pyodbc
from sqlalchemy import create_engine

engine = create_engine("mssql+pyodbc://user:password@host:port/databasename?driver=ODBC+Driver+17+for+SQL+Server")

cnxn = engine.connect()

使用相应的驱动程序

对我有用

好运!

答案 4 :(得分:0)

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};' 'Server=**SERVER NAME**;' 'Database=**DATABASE NAME**;' 'Trusted_Connection=yes;') 
cursor = conn.cursor() 

cursor.execute('SELECT * FROM Output3')

仅当您正确指定了相应的驱动程序,服务器和数据库名称时,此方法才有效!