1

I have database A for caching and B at the server, so I want to send a row from A to B and for that I need to generate the insert statement for already existed row in A.

below is what I want to accomplish

get insert select * from table where myId = 5;

and it should return

insert into table(myId,Col1,Col2,...) VALUES (5,'value1','value2',...);

I already had looked into this and this, that are not addressing my question. Thanks in advance!

Community
  • 1
  • 1
HAr
  • 461
  • 1
  • 3
  • 9
  • @duffymo what you are referring to is the copying of row from table1 to table2 on the same physical database, while mine is not the case. – HAr Feb 02 '16 at 12:56

1 Answers1

2

The sqlite3 command-line shell can generate such an output, but without column names, for queries:

sqlite> .mode insert MyTableName
sqlite> SELECT * FROM MyTable WHERE ID = 5;
INSERT INTO MyTableName VALUES(5,'value',NULL);

If you want the column names, you have to generate them manually:

SELECT 'INSERT INTO MyTable(a, b, c) VALUES (' ||
       quote(a) || ',' ||
       quote(b) || ',' ||
       quote(c) || ');'
FROM MyTable
WHERE ID = 5;
--> INSERT INTO MyName(a, b, c) VALUES (42,'value',NULL);

(The same string operations could be done in Java.)

If your program does not know the exact database schema, you can read the list of columns for each table with PRAGMA table_info, and construct the statement from that:

> create table MyTable(myId, Col1, Col2, [...]);
> pragma table_info(MyTable);
cid         name        type        notnull     dflt_value  pk        
----------  ----------  ----------  ----------  ----------  ----------
0           myId                    0                       0         
1           Col1                    0                       0         
2           Col2                    0                       0         
3           ...                     0                       0         
CL.
  • 173,858
  • 17
  • 217
  • 259
  • thank you for your response. but I cannot specify the columns as they are quite large in numbers for a table. Seems like I cannot achieve for what I asked the question. – HAr Feb 06 '16 at 21:31