zoukankan      html  css  js  c++  java
  • 6-Python操作MySQL-增(insert)-删(delete)-改(update)-查(select)

    增删改
    
    from pymysql import *
    
    def main():
        # 创建Connection连接
        conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
        # 获得Cursor对象
        cs1 = conn.cursor()
        # 执行insert语句,并返回受影响的行数:添加一条数据
        # 增加
        count = cs1.execute('insert into goods_cates(name) values("硬盘")')
        #打印受影响的行数
        print(count)
    
        count = cs1.execute('insert into goods_cates(name) values("光盘")')
        print(count)
    
        # # 更新
        # count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
        # # 删除
        # count = cs1.execute('delete from goods_cates where id=6')
    
        # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
        conn.commit()
    
        # 关闭Cursor对象
        cs1.close()
        # 关闭Connection对象
        conn.close()
    
    if __name__ == '__main__':
        main()
    
    # 查询一行数据
    from pymysql import *
    
    def main():
        # 创建Connection连接
        conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        # 获得Cursor对象
        cs1 = conn.cursor()
        # 执行select语句,并返回受影响的行数:查询一条数据
        count = cs1.execute('select id,name from goods where id>=4')
        # 打印受影响的行数
        print("查询到%d条数据:" % count)
    
        for i in range(count):
            # 获取查询的结果
            result = cs1.fetchone()
            # 打印查询的结果
            print(result)
            # 获取查询的结果
    
        # 关闭Cursor对象
        cs1.close()
        conn.close()
    
    if __name__ == '__main__':
        main()
    
    # 查询多行数据
    from pymysql import *
    
    def main():
        # 创建Connection连接
        conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        # 获得Cursor对象
        cs1 = conn.cursor()
        # 执行select语句,并返回受影响的行数:查询一条数据
        count = cs1.execute('select id,name from goods where id>=4')
        # 打印受影响的行数
        print("查询到%d条数据:" % count)
    
        # for i in range(count):
        #     # 获取查询的结果
        #     result = cs1.fetchone()
        #     # 打印查询的结果
        #     print(result)
        #     # 获取查询的结果
    
        result = cs1.fetchall()
        print(result)
    
        # 关闭Cursor对象
        cs1.close()
        conn.close()
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    js识别键盘操作
    抽奖活动 算法设计
    Eureka 配置项说明
    manjaro 更新chrome报签名错误
    manjaro系统上使用asdf安装php注意事项
    Failed to load config "react-app" to extend from.
    YarnV2 install
    银河麒麟安装达梦数据库失败Unable to load native library: libnsl.so.1: cannot open shared object file: No such file or directory
    Net5中使用Swagger
    编译Windows 版本的Redis 6.x
  • 原文地址:https://www.cnblogs.com/summer1019/p/11048168.html
Copyright © 2011-2022 走看看