Python Connection Database

Source: Internet
Author: User
Tags rollback

Python2
  • can be used MySQLdb
  • The code is as follows

    classsqlObject):def __init__( Self):Try: Self. conn=MySQLdb.Connect(Host=DB_IP, user=Db_user, passwd=Db_password, DB=Db_name,) Self. Conn.set_character_set (' UTF8 ') Self. cur=  Self. Conn.cursor () Self. Cur.execute (' SET NAMES utf8; ') Self. Cur.execute (' Set CHARACTER set UTF8; ') Self. Cur.execute (' SET Character_set_connection=utf8; ')except Exception  asE:RaiseE# Returns a two-dimensional tuple, each record as a tuple, and all the records to form a tuple    defExecuteQuery ( Self, Sqlcode):Try: Self. Cur.execute (Sqlcode) ResultSet=  Self. Cur.fetchall () Self. Conn.commit ()returnResultSetexcept Exception  asE: Self. Conn.rollback ()RaiseEdefExecuteupdate ( Self, SqlCode):Try: Self. Cur.execute (SqlCode) Self. Conn.commit ()except Exception  asE: Self. Conn.rollback ()RaiseEdef __del__( Self): Self. Conn.close ()
    Python3
  • Using Pymysql

    db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset=‘utf8‘= db.cursor()
    Specify the parameter name when the parameter is relatively long, or you will get an error
  • Specify parameters when the query results contain Chinese charset , otherwise garbled characters will appear.
  • When you write the results to a document, the Open function adds a parameter to the encoding specified encoding
  • Inquire

    =#返回所有结果=#返回单条数据

Python Connection Database

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.