如何使用 python 连接到 SQL 服务器数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39149243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I connect to a SQL server database with python?
提问by Federico Agudelo Mejia
Im trying to conennect to an sql database that its already created an that its located on a server. How can I connect to this database using python. Ive tried using java but I cant seem to get working either.
我试图连接到它已经创建了它位于服务器上的 sql 数据库。如何使用 python 连接到这个数据库。我试过使用 java,但我似乎也无法工作。
回答by davidejones
Well depending on what sql database you are using you can pip install pymssql for microsoft sql (mssql), psycopg2 for postgres (psql) or mysqldb for mysql databases Here are a few examples of using it
好吧,取决于您使用的 sql 数据库,您可以 pip install pymssql for microsoft sql (mssql),psycopg2 for postgres (psql) 或 mysqldb for mysql 数据库这里有几个使用它的例子
Microsoft sql
微软sql
import pymssql
conn = pymssql.connect(server=server, user=user, password=password, database=db)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(MemberID) as count FROM Members WHERE id = 1")
row = cursor.fetchone()
conn.close()
print(row)
Postgres
Postgres
import psycopg2
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port="5432")
cursor = conn.cursor()
cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1')
row = cursor.fetchone()
conn.close()
print(row)
mysql
mysql
import MySQLdb
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = conn.cursor()
cursor.execute('SELECT COUNT(MemberID) as count FROM Members WHERE id = 1')
row = cursor.fetchone()
conn.close()
print(row)