• python 中 mysql-connector 操作


    使用 pip 命令来安装 mysql-connector:
    python -m pip install mysql-connector
    
    开始演练:
    
    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="192.168.10.10",  # 数据库主机地址
        user="root",  # 数据库用户名
        passwd="123456",  # 数据库密码
        database="runoob_db"
    )
    myexec = mydb.cursor()
    
    #删除表
    sql = "drop table if exists sites"
    myexec.execute(sql)
    
    
    #更新表数据
    # sql = "update sites set url = 'http://www.tgbus.com' where url = 'https://www.taobao.com'"
    # myexec.execute(sql)
    # mydb.commit()
    
    # 删除记录
    # sql = "delete from sites where name = '178'"
    # myexec.execute(sql)
    # mydb.commit()
    # print(myexec.rowcount,"条记录删除")
    
    
    # 排序默认为升序,desc 为降序
    # sql = "select * from sites order by id desc limit 3 offset 1"
    # myexec.execute(sql)
    # myresult = myexec.fetchall()
    # for x in myresult:
    #     print(x)
    
    #where 条件使用
    # sql = "select * from sites where name='178'"
    # myexec.execute(sql)
    # myresult = myexec.fetchall()
    # for x in myresult:
    #     print(x)
    
    
    #查询数据
    # myexec.execute("select * from sites")
    # myresult = myexec.fetchall()
    # for x in myresult:
    #     print(x)
    
    
    #批量插入数据 批量插入使用 executemany() 方法
    # sql = "INSERT INTO sites (name,url) VALUES (%s,%s)"
    # val = [
    #     ('178', 'https://www.178.com')
    # ]
    # myexec.executemany(sql,val)
    # mydb.commit()
    # print(myexec.rowcount,"记录插入成功")
    # print("1条记录已插入,ID:", myexec.lastrowid)
    
    
    #单条插入数据
    # sql = "INSERT INTO sites (name,url) VALUES (%s,%s)"
    # val = ("RUNOOB","https://www.runoob.com")
    # myexec.execute(sql,val)
    # mydb.commit()
    # print(myexec.rowcount,"记录插入成功")
    
    # 创建数据库
    #myexec.execute("CREATE DATABASE runoob_db")
    
    # 查询数据库
    # myexec.execute("SHOW DATABASES")
    # for x in myexec:
    #     print(x)
    
    # 指定数据库增加表
    #myexec.execute("CREATE TABLE sites (name VARCHAR(255),url VARCHAR(255))")
    # myexec.execute("SHOW TABLES")
    # for x in myexec:
    #     print(x)
    
    #增加主键
    # myexec.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
    

      

  • 相关阅读:
    gcc 编译器常用的命令行参数一览
    linux下源代码分析和阅读工具比较
    Linux系统——C/C++开发工具及环境搭建
    GDB调试——经验总结
    gdb调试的艺术——Debug技巧
    命令__cp、scp(Secure Copy)
    常用shell脚本命令
    命令__查找、替换、删除
    UltraEdit 删除空行
    命令__shell数字-字符串比较
  • 原文地址:https://www.cnblogs.com/lixinliang/p/13815873.html
Copyright © 2020-2023  润新知