zoukankan      html  css  js  c++  java
  • python 连接mysql数据库:pymysql

    示例:import pymysql

    conn=pymysql.connect(
      host="127.0.0.1",     #数据库IP
      port=3306,         #数据库端口
      user="root",         #数据库用户名
      passwd="root",      #数据库密码
      db="testman",      #连接数据库名
      charset="utf8"      #数据库字符集
      )
    cursor=conn.cursor()    #使用cursor()方法获取数据库的操作游标(游标是记录操作哪个库、表、字段、时间等信息)


    #创建数据库的sql
    CreateDatabaseSql="create database if not exists test176 default charset utf8mb4 collate utf8_general_ci;"
    #创建表的sql
    CreateTableSql="create table tb_user_info (id int(6) not null,login_name varchar(12),pass_word varchar(16),create_date datetime)engine=innodb default charset=utf8mb4;"
    #修改表结构sql
    AlterSql="alter table tb_user_info add sex varchar2(6);"
    #删除表sql
    DropSql="drop table tb_user_info;"
    #插入数据的sql
    InsertSql="insert into tb_user_info values(1,'wq123','123456','2018-12-30');"
    #修改表数据
    UpdateSql="update tb_user_info set pass_word='123456' where login_name='wq123';"
    #删除表数据
    DeleteSql="delete from tb_user_info where login_name='wq123';"
    #查询表数据
    SelectSql="select * from tb_user_info;"


    try:
      cursor.execute(SelectSql)      #SelectSql可以是其他数据库操作变量,执行sql语句,返回的是影响行数
      OneData=cursor.fetchone()      #一条查询结果,返回类型为tuple
      AllData=cursor.fetchall()       #所有查询结果,返回类型为tuple:((login_name1,passwd1,),(login_name2,passwd2),),可遍历
      conn.commit()         #提交操作
      cursor.close()          #关闭游标
      conn.close()         #关闭数据库连接
    except pymysql.Error as e:
      print("mysql error %d:%s" %(e.args[0],e.args[1]))        #捕获异常(如数据库无法连接:ip、端口错误等)
      conn.rollback()       #报错时回退
      cursor.close()        #关闭游标
      conn.close()        #关闭数据库连接

  • 相关阅读:
    windows phone 网络开发三部曲(一)各种包的各种抓法
    Windows phone UI虚拟化和数据虚拟化(二)
    Windows phone UI虚拟化和数据虚拟化(一)
    LongListSelector 控件 在 wp7 和wp8中的不同之处
    wp8 longlistselector 动态加载datatemplate
    解读Python发送邮件
    浅谈Python时间模块
    中文分词技术一:概念
    MySQL常用命令
    初步认识Hive
  • 原文地址:https://www.cnblogs.com/whitemouseV2-0/p/11284386.html
Copyright © 2011-2022 走看看