Python method to import txt data to mysql
- 2020-05-07 19:55:30
- OfStack
This example shows how Python imports txt data into mysql. Share with you for your reference. Specific analysis is as follows:
Convert data from TXT text to MYSQL database, touch 1 time python first write something with Python 2.7
#!/usr/bin/python
#coding=utf-8
import _mysql,sys,io
def addCity(prov,city,tel,post):
try:
conn=_mysql.connect("192.168.1.99",'php','php');
conn.query("set names utf8");
conn.query("insert into `domain`.`postcode`(Province,City,TelCode,
PostCode)values('"+prov+"','"+city+"','"+tel+"','"+post+"')");
result=conn.use_result();
#print("version:%s" % result.fetch_row()[0])
conn.close()
except _mysql.Error,e:
print("Error %d:%s" % (e.args[0],e.args[1]))
sys.exit(1)
if __name__=="__main__":
f = open("data.txt", "r")
for line in f:
content=line.split(",");
print content[0],content[2]
addCity(content[0],content[1],content[2],content[3]);
f.close()
I hope this article has been helpful to your Python programming.