python将txt文件写入数据库_Python将txt文件输入到MySQL数据库中

本文介绍了使用Python将txt文件写入数据库的方法。首先说明了连接数据库前的准备事项,给出连接数据库的代码示例;接着展示了创建数据库表的代码;最后给出将txt文件内容写入数据库表的代码,包含文件读取、数据处理和插入操作。
摘要由CSDN通过智能技术生成

连接

连接数据库前,请先确认以下事项:

您已经创建了数据库 testdb. 在testdb数据库中您已经创建了表 employee employee表字段为 first_name, last_name, age, sex 和 income。 连接数据库testdb使用的用户名为 “testuser” ,密码为 “test123”,你可以可以自己设定或者直接使用root用户名及其密码,my用户授权请使用grant命令。 在你的机子上已经安装了 python mysqldb 模块。 如果您对sql语句不熟悉,可以访问我们的 sql基础教程

#!/usr/bin/python

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

import mysqldb

# 打开数据库连接

db = mysqldb.connect("localhost","testuser","test123","testdb" )

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

cursor = db.cursor()

# 使用execute方法执行sql语句

cursor.execute("select version()")

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

data = cursor.fetchone()

print "database version : %s " % data

# 关闭数据库连接

db.close()

创建数据库表

如果数据库连接存在我们可以使用execute()方法来为数据库创建表,如下所示创建表employee:

#!/usr/bin/python

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

import mysqldb

# 打开数据库连接

db = mysqldb.connect("localhost","testuser","test123","testdb" )

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

cursor = db.cursor()

# 如果数据表已经存在使用 execute() 方法删除表。

cursor.execute("drop table if exists employee")

# 创建数据表sql语句

sql = """create table employee (

first_name char(20) not null,

last_name char(20),

age int,

sex char(1),

income float )"""

cursor.execute(sql)

# 关闭数据库连接

db.close()

基本的知道后就直接粘贴了

#coding=utf-8

import mysqldb

#mysql的连接

conn = mysqldb.connect(

host='localhost',

port=3306,

user='root',

passwd='12345abcde',

db='test',

charset='utf8',

)

cur = conn.cursor()

f = open("matches.txt", "r")

while true:

line = f.readline()

if line:

#处理每行\n

line = line.strip('\n')

line = line.split(":")

print line

cur.execute(

"insert into meacthdata(first_name,last_name,number1,number2) values(%s,%s,%s,%s)",

[line[0], line[1], line[2], line[3]])

else:

break

f.close()

cur.close()

conn.commit()

conn.close()

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值