连接
连接数据库前,请先确认以下事项:
您已经创建了数据库 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()
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!