Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to a SQL server database with python? [closed]

Tags:

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.

like image 778
Federico Agudelo Mejia Avatar asked Aug 25 '16 15:08

Federico Agudelo Mejia


People also ask

Do we need to close DB connection in Python?

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [ conn. close() ], but you can explicitly close the connection if you wish. and similarly for cursors (my emphasis):

Which function is use to close the connection from database in Python?

To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.


1 Answers

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) 
like image 193
davidejones Avatar answered Oct 24 '22 12:10

davidejones