Python Pymysql Module Learning experience

Source: Internet
Author: User

Pymysql contains a pure python library of MySQL clients that are designed to replace MYSQLDB and work in Cpython,pypy and IronPython.

Pymysql official address:https://pypi.python.org/pypi/PyMySQL#documentation

Here is a simple example and description:

dbinfo={    'Host':'host_ip',    'Port': 3306,    'User':'user_name',    'Password':'Password',     'DB':'db_name',     'CharSet':'UTF8',}
defquerymysql (SQL):

#将数据库的信息当成字段传给connect (), which facilitates separation of data and functions, and can also write parameters directly in Connect () Conn= Pymysql.connect (* *DbInfo)
#建立连接后创建游标 cur=Conn.cursor ()
#执行sql语句, the SELECT statement also needs a fetch to get the data, otherwise it returns the number of data Cur.execute (SQL) Res=Cur.fetchall () cur.close ()
#sql语句不是自动提交的, manual commit required to remain modified Conn.commit ()
#执行sql语句后关闭连接 conn.close ()returnRessql='SELECT * FROM table_name'result=querymysql (SQL)Print(Result)

Here is an example of an official document that has been detailed, and I would simply add:

Importpymysql.cursors#Connect to the databaseConnection = Pymysql.connect (host='localhost', the user='User', Password='passwd', DB='DB', CharSet='UTF8MB4', Cursorclass=pymysql.cursors.dictcursor)#Cursorclass Select the format, dictionary, or list of returned data. #Try statement prevents assert interruptsTry:    #using the WITH statement avoids shutting down the connection operationWith Connection.cursor () as cursor:#Create a new recordsql ="INSERT into ' users ' (' email ', ' password ') VALUES (%s,%s)"cursor.execute (SQL, ('[email protected]','Very-secret'))    #connection is isn't autocommit by default. So-must commit to save    #your changes.Connection.commit () with Connection.cursor () as cursor:#Read a single recordsql ="SELECT ' id ', ' password ' from ' users ' WHERE ' email ' =%s"cursor.execute (SQL, ('[email protected]',)) Result=Cursor.fetchone ()Print(Result)finally: Connection.close ()

Python Pymysql Module Learning experience

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.