pymysql 操作

2020-03-19  本文已影响0人  清水秋香
import pymysql

#打开数据库连接
connection = pymysql.connect(host='127.0.0.1',user='root',passwd='wgz123',port=3306,db='classes')
#获取操作游标
try:
    with connection.cursor() as cursor:
        sql = '''
            insert into chaxun values('1993','1','1.4')
        '''
        cursor.execute(sql)
    connection.commit()
    with connection.cursor() as cursor:
        sql = """
            delete from chaxun where amount = '1.2';
        """
        cursor.execute(sql)
    connection.commit()

    with connection.cursor() as cursor:
        sql = '''
            update chaxun set year='1995' where amount = '1.3';
        '''
        cursor.execute(sql)
    connection.commit()

    with connection.cursor() as cursor:
        sql = '''
            select * from chaxun;
        '''
        cursor.execute(sql)
        print(cursor.fetchmany())
        print(cursor.fetchone())
        print(cursor.fetchall())
    with connection.cursor() as cursor:
        sql = '''
        create table if not exists test(
            id int auto_increment,
            name char(255),
            age int not null,
            primary key(id)
        )
        '''
        cursor.execute(sql)
    connection.commit()

except Exception as e:
    connection.rollback()
    raise e
finally:
    connection.close()
上一篇下一篇

猜你喜欢

热点阅读