Python Operations Database (MySQL)

Source: Internet
Author: User

1. Install MySQL Database

2. Execute pip install pymysql install pymysql Connection database

3, Python connection database specific operations:

ImportPymysql#1. Connect the MySQL IP port number password account databaseconn = Pymysql.connect (host=' 123. 456.789.00', the user='Root', passwd='123456',#Port must write int type hereport=3306, db='Test', charset='UTF8')#CharSet must write UTF8, cannot write utf-8

# 2, create cursors, cursors you think it's the warehouse manager. cur = conn.cursor (cursor=pymysql.cursors.dictcursor)

# 3, writing SQL statements sql = "INSERT into ' table ' (' id ', ' name ', ' phone ', ' addr ') VALUES (' 1 ', ' Mack ', ' 18612341241 ', ' Beijing ');" sql ="select * from Bt_stu limit 5;"sql = "SELECT * from Bt_stu where id=1;"

# 4, execute SQL Cur.execute (SQL)#Execute SQL statementConn.commit ()#Submit#The update Delete INSERT statement needs to be submitted

# 5, Get the result of SQL statement execution, it put the result in a tuple, each piece of data is also a tuple res = Cur.fetchall ()# Get all res = Cur.fetchone ()#gets only one result, the result of which is a 1-dimensional tuple
# There's only one piece of data, so use Fetchone, more than a single piece of data. Fetchall Print(RES)Print('Fetchall', Cur.fetchall ())

# 6, move cursor cur.scroll (0,mode='Absolute')#move the cursor to the frontCur.scroll (3,mode='relative')#moves the cursor, relative to the current position of the
# 7, close the connection, close the cursor Cur.close ()#Close CursorsConn.close ()#Close Connection

Python Operations Database (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.