Introduction to two common methods for connecting Python to a database

Source: Internet
Author: User

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:

 
 
  1. import psycopg2  
  2. conn = psycopg2.connect("dbname='dbname' user='username' 
    host='localhost' password='password'")  
  3. cur = conn.cursor()  
  4. cur.execute("select * from dbtable")  
  5. for row in cur:  
  6. print row[0]  
  7. conn.close() 

Connect Python to database ms SQL server:

Connect using pymssql

Sample Code:

 
 
  1. import psmssql  
  2. conn = psmssql.connect(host='yourhost', user='loginname', 
    password='password', database='dbname', charset='utf8')  
  3. cur = conn.cursor()  
  4. cur.execute('select * from dbtable')  
  5. for row in cur:  
  6. print row[0]  
  7. conn.close() 

The above describes how to connect to a database using Python.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.