python读取mysql数据库表_Python 操作MySQL数据库

环境

Anaconda3 Python 3.6, Window 64bit

目的

从MySQL数据库读取目标表数据,并处理

代码

# -*- coding: utf-8 -*-

import pymysql

# 配置数据库连接

dbconn=pymysql.connect(

host="***",

database="kimbo",

user="kimbo_test",

password="***",

port=3306,

charset='utf8'

)

# 使用cursor()方法获取操作游标

cursor = dbconn.cursor()

# 配置执行语句

sqlcmd1="drop table if exists zss_test;" \

"create table zss_test(" \

"ID bigint not null comment 'ID'," \

"col_name varchar(100) comment '列名'," \

"col_type varchar(100) comment '数据类型'," \

"update_time timestamp not null default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '更新时间');"

sqlcmd2="truncate table zss_test;insert into zss_test(id,col_name,col_type) VALUES (1,'star_type','string'),(2,'cust_type','string');"

try:

# 执行sql语句

cursor.execute(sqlcmd1)

cursor.execute(sqlcmd2)

dbconn.commit()

except:

# Rollback in case there is any error

dbconn.rollback()

#获得表中总记录数

res=cursor.execute("select * from zss_test")

print('总记录数:%d' % res +' 条。')

print("分别为--------->")

#打印表中的多条数据

# 使用 fetchone() 方法获取一条。

# 使用 fetchall() 方法获取全部

info=cursor.fetchall()

for i in info:

print(i)

# 关闭游标,关闭数据库连接

cursor.close()

dbconn.close()

结果如图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值