Get Insert Statement for existing row in MySQL
There doesn't seem to be a way to get the INSERT
statements from the MySQL console, but you can get them using mysqldump like Rob suggested. Specify -t
to omit table creation.
mysqldump -t -u MyUserName -pMyPassword MyDatabase MyTable --where="ID = 10"
In MySQL Workbench you can export the results of any single-table query as a list of INSERT
statements. Just run the query, and then:
- click on the floppy disk near
Export/Import
above the results - give the target file a name
- at the bottom of the window, for
Format
selectSQL INSERT statements
- click
Save
- click
Export
Since you copied the table with the SQL produced by SHOW CREATE TABLE MyTable, you could just do the following to load the data into the new table.
INSERT INTO dest_db.dest_table SELECT * FROM source_db.source_table;
If you really want the INSERT statements, then the only way that I know of is to use mysqldump http://dev.mysql.com/doc/refman/5.1/en/mysqldump.htm. You can give it options to just dump data for a specific table and even limit rows.
I wrote a php function that will do this. I needed to make an insert statement in case a record needs to be replaced after deletion for a history table:
function makeRecoverySQL($table, $id)
{
// get the record
$selectSQL = "SELECT * FROM `" . $table . "` WHERE `id` = " . $id . ';';
$result = mysql_query($selectSQL, $YourDbHandle);
$row = mysql_fetch_assoc($result);
$insertSQL = "INSERT INTO `" . $table . "` SET ";
foreach ($row as $field => $value) {
$insertSQL .= " `" . $field . "` = '" . $value . "', ";
}
$insertSQL = trim($insertSQL, ", ");
return $insertSQL;
}