Skip to content

Instantly share code, notes, and snippets.

@vlcinsky
Created April 29, 2014 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlcinsky/11391584 to your computer and use it in GitHub Desktop.
Save vlcinsky/11391584 to your computer and use it in GitHub Desktop.
Convert CSV file into SQL script
"""
Usage:
csv2sql.py [--table <tablename>] <csvfile>
Options:
--table <tablename> Name of table in database to import into [default: mytable]
Convert csv file with iperf data into sql script for importing
those data into MySQL database.
"""
from csv import DictReader
from docopt import docopt
if __name__ == "__main__":
args = docopt(__doc__)
fname = args["<csvfile>"]
tablename = args["--table"]
headers = ["timestamp",
"server_ip",
"server_port",
"client_ip",
"client_port",
"tag_id",
"interval",
"transferred",
"bandwidth"
]
sql = """insert into {tablename}
values ({timestamp},"{server_ip}",{server_port},"{client_ip}",{client_port},{tag_id},"{interval}",{transferred},{bandwidth});"""
with open(fname) as f:
reader = DictReader(f, headers, delimiter=",")
for rec in reader:
print(sql.format(tablename=tablename, **rec)) # python <= 2.6 will fail here
20140422105054 172.16.10.76 41065 172.16.10.65 5001 6 0.0-20.0 73138176 29215083
20140422105054 172.16.10.76 5001 172.16.10.65 56254 4 0.0-20.0 46350336 18502933
20140422105100 172.16.10.76 54550 172.16.10.50 5001 8 0.0-20.0 67895296 27129408
20140422105100 172.16.10.76 5001 172.16.10.50 58447 5 0.0-20.1 50937856 20292796
20140422105553 172.16.10.76 5001 172.16.10.65 47382 7 0.0-20.1 51118080 20358083
20140422105553 172.16.10.76 41067 172.16.10.65 5001 5 0.0-20.1 76677120 30524007
20140422105600 172.16.10.76 5001 172.16.10.50 40734 4 0.0-20.0 57606144 23001066
20140422105600 172.16.10.76 54552 172.16.10.50 5001 8 0.0-20.0 70123520 28019115
20140422110053 172.16.10.76 41070 172.16.10.65 5001 5 0.0-20.1 63438848 25284066
20140422110053 172.16.10.76 5001 172.16.10.65 46462 6 0.0-20.1 11321344 4497094
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment