26

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.

  • Stack Overflow focuses on *specific* questions, like "How do I use Django's ORM to connect to a SQL server?" (you can find lots of already-asked questions about such topics, eg. https://stackoverflow.com/questions/43430091/connecting-django-with-mssql-server). However, it's not the place to ask "there are five trillion libraries (slight exaggeration) for working with databases in Python: which should I use?" There are forums and comparison sites elsewhere on the web devoted to answering those questions: SO sticks to helping you once you pick one (and have trouble). – machineghost Jun 29 '19 at 16:24

1 Answers1

26

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

Microsoft 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

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

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)
davidejones
  • 1,869
  • 1
  • 16
  • 18
  • 2
    Step by step on configuring pymssql for python dev https://learn.microsoft.com/en-us/sql/connect/python/pymssql/step-1-configure-development-environment-for-pymssql-python-development?view=sql-server-2017 ...and thanks @davidejones – Chris Catignani May 28 '19 at 20:16