数据库
首页 > 数据库> > python_操作MySQL 初解

python_操作MySQL 初解

作者:互联网

# -*- coding: utf-8 -*-
# __author__ = "Allen"
import pymysql
con=pymysql.connect(
    host="localhost",
    user="root",
    port=3306,
    passwd="123",
    charset="utf8",
    db="test"
)
cur=con.cursor()
sql={
    "create":'create table if not  exists shu(name char(15)not null,sex char(10),age int,score int)default charset="utf8"',
    "insert":[
        'insert into shu values("小王","男",26,97)',
        'insert into shu values("小白","女",34,89)',
        'insert into shu values("小黄","女",22,95)',
        'insert into shu values("小黑","女",27,58)',
        'insert into shu values("小刘","男",24,76)',
        'insert into shu values("小讲","男",34,65)',
        'insert into shu values("小班","男",42,79)'
    ],
    "select":'select * from shu where sex="男";',
    "select1":'select * from shu where sex="女";',
    "select2":'select * from shu where score>80;',
    "update":'update shu set age=age+2;',
    "select3":'select * from shu;',
    "delete":'delete from shu where name="小讲";',
    "select4":'select * from shu order by age desc;',
    "select5":'select * from shu order by age asc;',
    "drop":'drop table if exists shu',
}
def for_out(cur):
    for i in cur:
        print(i)
    print( )
try:
    print("初始化数据库")
    print(sql["create"])
    cur.execute(sql["create"])

    for j in sql["insert"]:
        print(j)
        cur.execute(j)
    cur.execute(sql["select"])
    for_out(cur)

    cur.execute(sql["select1"])
    for_out(cur)

    cur.execute(sql["select2"])
    for_out(cur)

    cur.execute(sql["update"])
    for_out(cur)
    cur.execute(sql["select3"])
    for_out(cur)
    cur.execute(sql["delete"])
    for_out(cur)
    cur.execute(sql["select4"])
    for_out(cur)
    cur.execute(sql["select5"])
    for_out(cur)
    cur.execute(sql["drop"])
    for_out(cur)
except Exception as f:
    print(f)
    con.rollback()
con.close()
cur.close()

 

标签:insert,execute,shu,python,MySQL,初解,sql,out,cur
来源: https://www.cnblogs.com/zhichao123/p/11240715.html