概述
一、代码实现
python2使用MySQLdb模块
python3使用pymysql模块
代码用的是python2,去掉注释可换成python3
#-*- encoding: utf-8 -*-
'''
MysqlUtil.py
Created on 2020/8/27 20:33
Copyright (c) 2020/8/27, Google Copy right
@author: com
'''
import MySQLdb
# import pymysql
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="test", charset="utf8")
# db = pymysql.connect(host="localhost", user="root", passwd="123456", db="test", charset="utf8")
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("MySQL Version : %s" % data)
cursor.execute("SELECT * FROM user")
result = cursor.fetchall()
for row in result:
print("%d t %s t %d" % row)
db.commit()
except:
db.rollback()
finally:
db.close()
二、执行结果
三、测试数据
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 50722
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 50722
File Encoding : 65001
Date: 22/09/2020 16:44:52
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '新中国', 70);
INSERT INTO `user` VALUES (2, '吴京', 50);
INSERT INTO `user` VALUES (3, '李小龙', 32);
INSERT INTO `user` VALUES (4, '科比', 43);
INSERT INTO `user` VALUES (5, '胡歌', 40);
INSERT INTO `user` VALUES (6, '汪大东', 30);
INSERT INTO `user` VALUES (7, '汪大东', 30);
SET FOREIGN_KEY_CHECKS = 1;
最后
以上就是飞快帆布鞋为你收集整理的python2和python3连接MySQL数据库的全部内容,希望文章能够帮你解决python2和python3连接MySQL数据库所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复