pymysql操作mysql数据库

首先安装mysql
安装pymsql
#!/usr/bin/python3
# -*- coding:utf-8 -*-

#python2操作数据库需要mysqldb
#python3-------》pymsql

import pymysql

#创建数据库链接
dbcon=pymysql.connect(host='127.0.0.1',user='root',password='123123',port=3306)

with dbcon:
    #创建游标
    cur=dbcon.cursor()
    cur.execute('SELECT VERSION()')
    version = cur.fetchone()
    print("数据版本:", version)
    # 创建数据库,数据库名csdn
    cur.execute("create database IF NOT EXISTS CSDN;")

    cur.execute("use CSDN;")

    #创建表格Writers(如果不存在)
    cur.execute("CREATE TABLE IF NOT EXISTS Writers(Id INT PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(25))")

    #插入数据
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
    cur.execute("INSERT INTO Writers(Name) VALUES('hONORE DE bALZAC')")
    # cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
    # cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
    # cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
    #删除
    cur.execute("delete from Writers where Name = 'hONORE DE bALZAC'")
    #修改
    cur.execute("update Writers set Name = 'Jack London2' where Name = 'Jack London'")

    #查询数据
    cur.execute("select * from Writers")
    # 查询数据库多条数据
    print("查询的数据库内容:")
    result = cur.fetchall()
    for data in result:
        print(data)
    cur.close()
原文地址:https://www.cnblogs.com/Lijcyy/p/9903836.html