Python3 version of MySQL operation

Source: Internet
Author: User

1. Connecting Mysql:import Pymysql

Conn=pymysql.connect ("localhost", "root", "password", "database name") #打开数据库 connection)

Cursor=db.cursor () #使用cursor () method to create a cursor object cursors)

2. Query data

Conn.query () Conn.commit () Conn.close () conn=pymysql.connect (=,=,=,=) cur=conn.cursor () Cur.execute () R cur:     (, (Cur.rownumber))     (+ (r[]) + + (r[))    cur.close ()     conn.close ()       3, inserting data import pymysql#  Open database connection db =  Pymysql.connect ("localhost", "testuser", "test123", "TESTDB"  ) #  use the cursor () method to get the operation cursor  cursor =  db.cursor () # sql  INSERT statement sql =  "" "Insert into employee (FIRST_NAME,          last_name, age, sex, income)           VALUES  (' Mac ',  ' Mohan ', 20,  ' M ',  2000) "" "try:    #  Execute SQL statement    cursor.execute (SQL)    #  commit to database execution     db.commit () except:   #  rollback    db.rollback () #  If an error occurs Close database connection db.close ()    &nbSP; 4, create data table  import pymysql#  Open database connection db = pymysql.connect ("localhost", "testuser", " Test123 "," TESTDB " )  #  create a Cursor object using the  cursor ()   Method  cursorcursor = db.cursor (  #  Use the  execute ()   method to execute  sql, or delete cursor.execute if the table exists ("Drop table if exists  employee ")  #  CREATE table with preprocessing statements sql = " "" create table employee  (          first_name  char ( NOT NULL,   )       last_name  char (,       )   age int,           sex char (1),          INCOME FLOAT ) "" "Cursor.execute (SQL) #  Close database connection Db.close ()


This article is from the "Python installation of various Libraries" blog, reproduced please contact the author!

Python3 version of MySQL operation

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.