PyMySQL 通过键盘插入记录到MYSQL(INSERT into····)

import pymysql

# 把sql语句放在类中仅仅是为了方便折叠
class Oper_Sql:
    # 插入数据预处理方式
    insert = 'insert into self_user(id,name,sex,age,birthday) values(%s,%s,%s,%s,%s)'


def main():
    conn = pymysql.connect(
        host='localhost',  # 主机名
        port=3306,  # 端口号
        user='root',  # 用户名
        password='root',  # 密码
        charset='utf8',  # 字符集
        db='scott',  # 连接用户
        cursorclass=pymysql.cursors.DictCursor  # 改变为字典对象
    )
    print(conn)  # 输出连接对象地址表示连接成功
    insert_count = int(input('输入您要插入的总条数: '))
    try:
        while insert_count > 0:
            id = input('请输入id: ')
            name = input('亲输入您的姓名: ')
            sex = input('请输入您的性别(male or female): ')
            age = input('请输入您的年龄: ')
            birthday = input('请输入出生日期: ')
            with conn.cursor() as cursor:
                # cmd = conn.cursor()
                cursor.execute(query=Oper_Sql.insert, args=[id, name, sex, age, birthday])
                for row in cursor.fetchall():
                    id = row[0]
                    name = row[1]
                    sex = row[2]
                    age = row[3]
                    birthday = row[4]
                print('用户id: %s 用户名: %s 用户性别: %s 用户年龄: %s 用户出生日期: %s' % (id, name, sex, age, birthday))
                insert_count -= 1
                conn.commit() # 事务操作必须提交,否则数据库不生效
    except Exception as err:
        print(err)
        
    finally:
        # 资源需要关闭很有必要
        conn.close()


if __name__ == '__main__':  #
    main()

'''
字符集乱码:

    +------+-----------+--------+------+------------+
    | id   | name      | sex    | age  | birthday   |
    +------+-----------+--------+------+------------+
    | 1001 | aidou     | male   | 32   | 2020-02-23 |
    | 1002 | moli      | female | 12   | 2020-03-23 |
    | 1003 | ali       | male   | 32   | 2020-03-04 |
    | 1004 | 鐜嬪畯鏂?   | male   | 19   | 1996-05-04 |
    +------+-----------+--------+------+------------+
    
解决方案: 

 1. 显示当前字符集
 
    mysql> show variables like 'char%';
    
 2. set character_set_results=gb2312;
 
    mysql> select * from self_user;
    
    +------+--------+--------+------+------------+
    | id   | name   | sex    | age  | birthday   |
    +------+--------+--------+------+------------+
    | 1001 | aidou  | male   | 32   | 2020-02-23 |
    | 1002 | moli   | female | 12   | 2020-03-23 |
    | 1003 | ali    | male   | 32   | 2020-03-04 |
    | 1004 | 乱码字符       | male   | 19   | 1996-05-04 |
    +

'''

  • insert :
    在这里插入图片描述
  • 客户端查询结果:
    在这里插入图片描述
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值