Python连接Mysql数据库Demo

前言

这个必须要了解一下,
老保存到本地根本不是办法
简单的查询,新增,先了解基本写法

创建数据库

就算使用java也不会在代码创建数据库啥啥的,
所以这里都不去了解怎么在代码创建数据库,表之类的
直接手动去创建

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名字',
  `age` int(3) NULL DEFAULT NULL COMMENT '年龄',
  `sex` int(1) NULL DEFAULT 0 COMMENT '性别,0未知,1男,2女',
  `createtime` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户测试表' ROW_FORMAT = Compact;

简简单单搞点数据

INSERT INTO `tb_user` VALUES (1, '张三', 12, 1, '2020-04-03 11:03:03');
INSERT INTO `tb_user` VALUES (2, '李四', 34, 0, '2020-04-03 11:03:13');
INSERT INTO `tb_user` VALUES (3, '王五', 45, 2, '2020-04-03 11:03:24');
INSERT INTO `tb_user` VALUES (5, '小红', 12, 1, '2020-04-03 13:39:44');

编写代码


# @Author: GMaya

import pymysql
import datetime

# 打开数据库连接
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='python', charset='utf8')


# 查询方法
def seleteUser():
    # 使用cursor方法创建一个游标
    cursor = db.cursor()
    sql = "select * from tb_user"
    cursor.execute(sql)
    data = cursor.fetchall()
    for d in data:
        id = d[0]
        name = d[1]
        age = d[2]
        sex = d[3]
        createtime = d[4]
        print(id, name, age, sex, createtime)
    cursor.close()
    db.close()
    return data


def insertUser(name, age, sex, createTime):
    # 使用cursor方法创建一个游标
    cursor = db.cursor()
    sql = "insert into tb_user(name,age,sex,createtime) values (%s,%s,%s,%s) "
    try:
        # 执行sql语句;使用构造参数防止sql注入!
        row = cursor.execute(sql, (name, age, sex, createTime))
        print("影响条数:%s" % row)
        # 提交到数据库执行
        db.commit()
    except:
        # 发生错误时回滚
        db.rollback()
    # 关闭
    cursor.close()
    db.close()


if __name__ == '__main__':
    # 查询
    # data = seleteUser()
    # 新增
    insertUser('小红', 12, 1, datetime.datetime.now())


总结

datetime 模块

获取当前时间年月日时分秒
now(…):返回当前日期时间的datetime对象

datetime.datetime.now()

pymysql模块

获取新增主键id

cursor.lastrowid

获取查询全部结果

cursor.fetchall()

获取查询结果第一条

cursor.fetchone()
发布了70 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/gfl1427097103/article/details/105291775