In actual use, the Python programming language often encounters operations related to databases. Today, we will introduce two common methods for connecting Python to the database. I hope my friends can learn more from them.
Connect Python to postgresql:
Use psycopg2 to connect
Sample Code:
- import psycopg2
- conn = psycopg2.connect("dbname='dbname' user='username'
host='localhost' password='password'")
- cur = conn.cursor()
- cur.execute("select * from dbtable")
- for row in cur:
- print row[0]
- conn.close()
Connect Python to database ms SQL server:
Connect using pymssql
Sample Code:
- import psmssql
- conn = psmssql.connect(host='yourhost', user='loginname',
password='password', database='dbname', charset='utf8')
- cur = conn.cursor()
- cur.execute('select * from dbtable')
- for row in cur:
- print row[0]
- conn.close()
The above describes how to connect to a database using Python.