MySQL:用python操作MySQL
2016-07-25 14:47
525 查看
例:将一个txt文件里的结构化数据,逐行输入到MySQL数据库中
import pymysql def code2sql(): f = open('ActivationCode.txt', 'r') #连接上数据库 conn = pymysql.connect(user='root', passwd=' ') cursor = conn.cursor() #开始进行MySQL操作 #创建一个数据库 cursor.execute('create database if not exists accode') #使用创建的数据库 cursor.execute('use accode') #创建一张表 cursor.execute('create table accode(id int auto_increment primary key, code varchar(10))') for line in f.readlines(): #逐行插入一条数据 cursor.execute('insert into accode (code) values (%s)', line.strip()) #执行命令 conn.commit() f.close() #关闭数据库 cursor.close() conn.close() #如果直接运行该py文件,则运行code2sql函数 if __name__ == '__main__': code2sql()
相关文章推荐
- pythonparse 配置文件读取
- python2.7安装numpy报错:is not a supported wheel on...
- python2 和python3共存下问题
- Python 类货币四舍五入规则
- Python基础知识
- python布尔运算记录
- 我的python学习--第四天
- python数据库操作(1)--Mysql/Sqlite--DB-API
- 循序渐进Python3(二) -- 数据类型
- Python黑帽编程1.3 Python运行时与包管理工具
- python安装配置及HelloWorld
- Python面向对象习题
- Python 第一章 基础知识
- Python 第一章 基础知识
- Python 第一章 基础知识
- Python萌手册
- Ubuntu下protobuf及其python runtime的安装
- Python黑帽编程1.3 Python运行时与包管理工具
- Python学习进程(14)异常处理
- Python 多线程下载脚本