Home >Backend Development >Python Tutorial >Summary of python operation mysql code

Summary of python operation mysql code

不言
不言Original
2018-06-02 14:53:131317browse

This article shares with you the steps of operating mysql in python and related example codes. Friends in need can refer to it.

Install module

windows:pip install pymysql

ubuntu:sudo pip3 install pymysql

Python operation mysql steps

import pymysql

(1) Link to mysql database

db = pymysql.connect(host name, user name, password, database name)

( 2) Set character encoding

db.set_charset('utf8')

(3) Create cursor object

cursor = db.cursor()

(4) Prepare sql statement

sql = '...'

(5) Execute sql statement

cursor.execute(sql)

( 6) Get all result sets

cursor.fetchall()

(7) Get one result set

cursor.fetchone()

(8) Get the number of affected rows

cursor.rowcount

(9) Close the database link

db.close()

pymysql thing Processing

Transaction processing is enabled by default

Requires submission or rollback

Complete operation

import pymysql
db = pymysql.connect('127.0.0.1','root','123456','hz03')
db.set_charset('utf8')
cursor = db.cursor()
try:
  sql = 'insert into goods values(null,1,"商品名称",12.1)'
  cursor.execute(sql)
  db.commit()
except:
  db.rollback()
print(cursor.rowcount)
db.close()

The above is the detailed content of Summary of python operation mysql code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn