Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

android - How to copy only the table structure?

I want to create a database. It has up to 9 tables in future it may exceed. But the structure (number of columns and column name) of table is same for all tables. I know that there is an option to copy the structure of table and rename it and use it but I don't know how to do it exactly. Please give me the relevant answer so that it reduces my code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could extract the columns from the base table via PRAGMA table_info (<yourtable>)

e.g.

String sqlstr = " PRAGMA table_info (" + table_name + ")";
        Cursor csr = db.rawQuery(sqlstr, null);

The resultant cusors has rows with columns :-

cid (rowid)

name (name of the column)

type (column type e.g. INTEGER)

notnull (0 if can be null)

dflt_value (default value if one)

pk (0 if not part of the primary key otherwise 1,2... if part of the primary key)

You could then build the SQL from this.


Another alternative could be to extract the SQL used to create the table via :-

SELECT sql FROM sqlite_master WHERE type='table' AND name='<yourtable>'

You could then alter the resultant SQL, changing the base table name to the new table name.


A third option is to copy the table using something like

CREATE TABLE newtable AS SELECT * FROM basetable WHERE 0

However, this isn't a full comprehensive copy of the structure, e.g. primary keys aren't created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...