Import data to MySQL using Python

Source: Internet
Author: User
Import data to MySQL using Python

From converting TXT text to MySQL database, Python used python2.7 for the first time.
Originally, py3k is used. The database link used in the result does not support 3 K. A 3 K MySQL driver is downloaded online, and the compilation fails.

#!/usr/bin/python#coding=utf-8import _mysql,sys,iodef 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()
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.