Python Basics Summary-using MySQL

Source: Internet
Author: User

Python operation MySQL, very convenient, using the MYSQLDB library, the basic operation is as follows:

Inquire:

1 Try:2conn = MySQLdb.connect (Host=self.ip, User=self.username,passwd=self.password, Db=self.dbname, port=self.port)3Cur =conn.cursor ()4 cur.execute (SQL)5rows =Cur.fetchall ()6data =rows7 exceptMysqldb.error, E:8     PrintStr (e)9     Print "connet MySQL db error ..."TenSys.exit ()

Insert data:

Try :     = MySQLdb.connect (Host=self.ip, User=self.username, Passwd=self.password, Db=self.dbname, port=self.port)    = conn.cursor ()    cur.execute (SQL, value)    conn.commit ()    conn.close ()    cur.close () except Mysqldb.error, E:     Print Str (e)     Print " Execute MySQL db error ... "     sys.exit ()

Use Utf-8 to solve the coding problem when using the process of coding:

Conn.set_character_set ('utf8') cur.execute ('set NAMES UTF8; ' ) Cur.execute ('set CHARACTER set UTF8; ' ) Cur.execute ('SET Character_set_connection=utf8; ')

And the problem with the backslash, MySQL by default, the backslash escaped, my workaround is to replace the backslash with a double backslash:

DataPath = Datapath.replace ('\ \'\\\\')

The MySQL statement needs to format the string, and the SQL string for the query needs to represent the variable placeholder with%, but Python seems to have to use%s

Executemany also supports multiple data insertions at the same time, but I'm not using this because it's easy to add loops outside.

Python Basics Summary-using MySQL

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.