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()

结果如图:

 

posted @ 2017-03-11 15:48  Kimbo  阅读(334)  评论(0编辑  收藏  举报