欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用pymysql(使用一)

程序员文章站 2022-03-03 16:15:30
...

创建数据表

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()
知识在于点滴积累