Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to iterate through a MySQL table with Python?
    primarykey
    data
    text
    <p>I have a Python script which uses the MySQLdb interface to load various CSV files into MySQL tables.</p> <p>In my code, I use Python's standard CSV library to read the CSV, then I insert each field into the table one at a time, using an <code>INSERT</code> query. I do this rather than using <code>LOAD DATA</code> so that I can convert null values and other minor clean-ups on a per-field basis.</p> <p>Example table format:</p> <pre><code>`id_number` | `iteration` | `date` | `value` 102 | 1 | 2010-01-01 | 63 102 | 2 | 2010-01-02 | NULL 102 | 3 | 2010-01-03 | 65 </code></pre> <p>The null value in the second iteration of <code>id_number = 102</code> represents a case where <code>value</code> hasn't changed from the previous day i.e. <code>value</code> remains 63.</p> <p>Basically, I need to convert these null values to their correct values. I can imagine 4 ways of doing this:</p> <ol> <li><p>Once everything is inserted into the table, run a MySQL query that does the iterating and replacing all by itself.</p></li> <li><p>Once everything is inserted into the table, run a MySQL query to send some data back to Python, process in Python then run a MySQL query to update the correct values.</p></li> <li><p>Do the processing in Python on a per-field basis before each insert.</p></li> <li><p>Insert into a temporary table and use SQL to insert into the main table.</p></li> </ol> <p>I could probably work out how to do #2, and maybe #3, but have no idea how to do #1 or #4, which I think are the best methods as it then requires no fundamental changes to the Python code.</p> <p>My question is A) which of the above methods is "best" and "cleanest"? (Speed not really an issue.) and B) how would I achieve #1 or #4?</p> <p>Thanks in advance :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload