Convert sql to csv7/24/2023 ![]() Note that the SQL commands must be wrapped in double quotes. The -c flag can be used to run advanced SQL commands such as a LEFT JOIN, if desired but must have a basic SQL query at a minimum. Usage on the command line is as follows: $ python /path/to/script.py -i "/path/to/database.sql" -o "/path/to/output.csv" -c "select * from mydata" Parser.add_argument("-c","-command", help="SQL command", required=True) Parser.add_argument("-o", "-output", help="Output CSV file.", required=False) Parser.add_argument("-i", "-input", help="Input SQL file.", required=True) Parser = argparse.ArgumentParser(description="Convert a SQL file to a CSV file") To do this, I utilised the argparse utility and modified the script as follows: import sqlite3 From what I understand, it is fairly easy to export/convert a dataset/result set to CSV using a stringbuilder. Rather than hard-coding commands and variables into the script, it’s better to parse them as variables via the command line. I have found several links, such as this and this, which converts excel to CSV (however I can now skip this step, as I can just convert the resultset to CSV, with no need for the excel file), I also found this link. The entire code is as follows: import sqlite3Ĭonnection = nnect('/path/to/database.sql')Ĭolnames = for desc in scription] Therefore a colnames parameter is created to allow just the column name to be added to the output as a column header in the CSV file. ![]() ![]() It is based on Till Hoffman’s code with modifications to extract column names.Ĭolumn names are encoded in the scription parameter, but this actually contains a list of tuples, of which column_name is the first. ![]() There are quite a few Python scripts available that will convert a SQL database file into a CSV, but I have found the below code to be quite good. Nifty Python code that converts a SQL database file into a CSV file and includes column headers.
0 Comments
Leave a Reply. |