版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/84486963
一 往一个文件写数据
1 代码CodeInFile.py
# -*- coding:utf-8 -*-
class CodeInFile():
def __init__(self,name,code,database):
self.rootdir='E:\Python\MySQLControler'
File=open('%s/code'%self.rootdir,'w')
File.write('%s\t'%name)
File.write('%s\t'%code)
File.write('%s'%database)
File.close()
if __name__=='__main__':
test=CodeInFile('root','123456','test')
2 测试结果
root 123456 test
二 从文件读数据
1 代码ReadCode.py
# -*- coding:utf-8 -*-
class ReadCode():
def __init__(self):
self.rootdir = 'E:\Python\MySQLControler'
File=open('%s/code'%self.rootdir,'r')
self.Line=File.readline().split()
File.close()
def return_line(self):
return self.Line
if __name__=='__main__':
test=ReadCode()
print test.return_line()
2 测试结果
D:\Python27\python.exe E:/Python/MySQLControler/WriteAndReadFile/ReadCode.py
['root', '123456', 'test']
三 从文件读出数据用来连接数据库
1 代码Connect.py
# -*-coding:utf-8 -*-
import MySQLdb
from ReadCode import ReadCode
class Connect():
def __init__(self,database,sql):
readcode=ReadCode()
name=readcode.return_line()[0]
code=readcode.return_line()[1]
db=MySQLdb.connect("localhost","%s"%name,"%s"%code,"%s"%database)
cursor=db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
if __name__=='__main__':
test=Connect("test","insert into create_user(email) "
"VALUES('[email protected]')")
2 测试结果