in reply to Writing NULL values to a MySQL record via DBI

ureco:

In addition to using placeholders, you'll also benefit from using prepared statements. It's pretty simple to do, because as you surmised, there's a one-to-one relationship between the list of values you provide and the question mark in the SQL:

# Prepare your statement at the start of your program my $ST = $DB->prepare(q{ REPLACE INTO met_office_raw_data SET observation_datetime_utc = ?, observation_datetime_local = ?, observation_datetime = ?, station_id = ?, station_name = ?, temp_c = ?, dewpoint_c = ?, humidity_rh = ?, wind_dir_compass = ?, wind_speed_mph = ?, wind_gust_mph = ?, visibility_metres = ?, pressure_hpa = ?, pressure_tendency = ?, weather_type = ? }); while (....) { # Then for each reading, get the values my ( $file_obs_datetime_utc, $file_obs_datetime_local, $file_obs_datetime, $file_station_id, $file_station_name, $file_temp_c, $file_dewpoint_c, $file_humidity_rh, $file_wind_dir_compass, $file_wind_speed_mph, $file_wind_gust_mph, $file_visibility_metres, $file_pressure_hpa, $file_pressure_tendency, $file_weather_type ) = get_my_data(); # and write them to the table $ST->execute( $file_obs_datetime_utc, $file_obs_datetime_local, $file_obs_datetime, $file_station_id, $file_station_name, $file_temp_c, $file_dewpoint_c, $file_humidity_rh, $file_wind_dir_compass, $file_wind_speed_mph, $file_wind_gust_mph, $file_visibility_metres, $file_pressure_hpa, $file_pressure_tendency, $file_weather_type ); }

It's as easy as that. In fact, it's usually simpler: It's often easy enough to arrange that the order of values needed by the SQL operation matches that of your function that retrieves data. In that case, the while loop can boil down to:

while (....) { # Then for each reading, get the values my @data_fields = get_my_data(); # and write them to the table $ST->execute(@data_fields); }

(Assuming you're not using the variable names elsewhere in your code.)

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Writing NULL values to a MySQL record via DBI
by ureco (Acolyte) on Feb 27, 2015 at 16:51 UTC
    I like the look of this actually, makes for nice neat code. I'll look to adopt this into my script as well. With all the SQL statements as you say up near the beginning of the script they are easily found for making changes. Thanks for the advice.