Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm attempting to connect with a SQL database that it's now made and that is situated on a server. How might I associate with this database utilizing python? I've taken a stab at utilizing java however I can't get working all things considered.

1 Answer

0 votes
by (26.4k points)

Well depending upon what sql database you are utilizing you can pip introduce pymssql for microsoft sql (mssql), psycopg2 for postgres (psql) or mysqldb for mysql databases. Here are a couple of instances 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)

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...