Particles

pymysql模块学习

#Pymysql

  • 用于连接mysql数据库

#连接数据库

data_ip = "192.168.34.128"
data_name = "lch"
data_pwd = "lch123"
database = "day35_work"
import pymysql #导入模块
db = pymysql.connect(data_ip,data_name,data_pwd,database) #打开数据库连接
cursor = db.cursor()  #创建一个游标对象
create_book_sql = 
"""
create table book02(name char(16),owner char(16),press char(16),price int(5),date date)
"""
cursor.execute(create_book_sql) #执行create_book_sql

#增

import pymysql
db = pymysql.connect(data_ip,data_name,data_pwd,database) #打开数据库连接
cursor = db.cursor() #创建一个游标对象
insert_book02_sql = """
insert into book02 values
("学python从开始到放弃","alex","人民大学出版社",50,20180701),
("学mysql从开始到放弃 ","egon","北京工业地雷出版社",60,20180603),
("学html从开始到放弃","alex","机械工业出版社",20,20180401),
("学css从开始到放弃","wusir","机械工业出版社",120,20180502),
("学js从开始到放弃","wusir","机械工业出版社",100,20180730)
"""
try:
    cursor.execute(insert_book02_sql) #执行语句
    db.commit() #事物号提交
except:
    db.rollback()  #若报错,事物号回滚  
db.close() ##关闭数据库连接

#删

import pymysql
db = pymysql.connect(data_ip,data_name,data_pwd,database)
cousor = db.cursor()
delete_sql = "delete from book02 where price = 20"
try:
    cousor.execute(delete_sql)
    db.commit()
except:
    db.rollback()
db.close()

#改

import pymysql
db = pymysql.connect(data_ip,data_name,data_pwd,database)
cousor = db.cursor()
update_sql = "update book02 set price = 500 where price = 50"
try:
    cousor.execute(update_sql)
    db.commit()
except:
    db.rollback()
db.close()

#查

import pymysql
db = pymysql.connect(data_ip,data_name,data_pwd,database)
cursor = db.cursor()
sleetc_sql = "select * from book02"
try:
    cursor.execute(sleetc_sql)
    data = cursor.fetchall() #获取所有数据
    for i in data:  
        print(i)
except:
    print("ERROR")
db.close()

posted @ 2019-02-22 11:03  Na_years  阅读(85)  评论(0编辑  收藏  举报