使用pymysql

Posted lshnice

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用pymysql相关的知识,希望对你有一定的参考价值。

创建数据表

import pymysql

db = pymysql.connect("localhost","root","","hank")

cursor = db.cursor()

cursor.execute("DROP TABLE IF EXISTS leo")

sql = """CREATE TABLE leo (
            FIRST_NAME CHAR(20) NOT NULL,
            LAST_NAME CHAR(20),
            AGE INT,
            SEX CHAR(1),
            INCOME FLOAT)"""

cursor.execute(sql)

db.close()

新增数据

import pymysql

db = pymysql.connect("localhost","root","","hank")

cursor = db.cursor()

sql = """INSERT INTO leo(
         FIRST_NAME,LAST_NAME,AGE,SEX,INCOME)
         VALUES(‘JOE‘,‘B‘,20,‘F‘,4000) """

try:
    #执行sql语句
    cursor.execute(sql)
    #提交到数据库执行    
    db.commit()

except:
    #如果发生数据库执行
    db.rollback()

db.close()

mysql> select * from leo;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |
+------------+-----------+------+------+--------+
| Mike | A | 30 | M | 6000 |
| JOE | B | 20 | F | 4000 |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)


查询

import pymysql

db = pymysql.connect("localhost","root","","hank")

cursor = db.cursor()

sql = "SELECT * FROM leo "

try:
    #执行SQL语句    
    cursor.execute(sql)
    #获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        #打印结果
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" %  (fname,lname,age,sex,income))

except:
    print("Error:unable to fetch data")

fname=Mike,lname=A,age=30,sex=M,income=6000
fname=JOE,lname=B,age=20,sex=F,income=4000


数据库更改

import pymysql

db = pymysql.connect("localhost","root","","hank")

cursor = db.cursor()

sql = "UPDATE leo SET AGE = AGE + 1 WHERE SEX = ‘%c‘" % (‘M‘)  #找到sex性别为M的更新其年龄+1

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()

mysql> select * from leo;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |
+------------+-----------+------+------+--------+
| Mike | A | 31 | M | 6000 |
| JOE | B | 20 | F | 4000 |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)


删除操作

import pymysql

db = pymysql.connect("localhost","root","","hank")

cursor = db.cursor()

sql = "delete from leo where name = hankleo"

try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()















以上是关于使用pymysql的主要内容,如果未能解决你的问题,请参考以下文章

pymysql使用

在python中使用pymysql连接数据库

PyMySQL的使用详解

Python之PyMySQL的使用

Python中pymysql基本使用

pymysql模块