How do I connect to a SQL server database with python?
<p>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.</p>

<p>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</p>

<p>Microsoft sql</p>

<pre><code>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)
</code></pre>

<p>Postgres</p>

<pre><code>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)
</code></pre>

<p>mysql</p>

<pre><code>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)
</code></pre>

python sql-server database database-connection