How to get table information in a database (SQLite) [duplicate] - java

This question already has answers here:
How can I list the tables in a SQLite database file that was opened with ATTACH?
(17 answers)
Closed 7 years ago.
I'm new to SQLite. I'm using it in Eclipse(Java)just in case this is relevant.
Now my problem is that i have a *.db file and know nothing about its content. I would like to know which way i can get some information about the tables inside. Otherwise it seems to be imposible to read in the database correctly by a SELECT Query. So basically my problem is just this part
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM ???????;" );
while ( rs.next() ) {
int id = rs.getInt("id");
..

1. Understand the Schema of your Database
Open the terminal in the location of your .db file.
Enter the following command to start the SQLite Console.
sqlite3 NameOfDatabase.db
1.1 All tables
Then give the following command to the console:
.schema
This will give you all the information you need about all of your tables, including the data type of the fields. In other words, the above command will give you, your database schema.
An output example of the above command is the following:
CREATE TABLE log (ID INTEGER PRIMARY KEY AUTOINCREMENT, userID INTEGER, cardID INTEGER, eventID INTEGER, nameOnTicket TEXT, pricePaid REAL);
CREATE TABLE card (cardID INTEGER PRIMARY KEY AUTOINCREMENT, cardNum TEXT, securityCode TEXT, expiryMonth INTEGER, expiryYear INTEGER, addressID INTEGER, userID INTEGER);
It actually returns the command to re-create the tables, so that is also handy if you would like to output the queries to re-create your tables or to create a documentation for your database/application, but also to understand the structure and the table of your database.
1.2 Specific table
Additionally, you can see the schema of a specific table, using the following command:
.schema TableName
Which will return back the schema of the TableName table.
2. Integrate SQLite with Eclipse
Another option is to integrate your SQLite Database with Eclipse bellow you can find the steps to do that. The steps bellow have been copied here from the official Eclipse wiki, that you can find here.
1) Download the SQLite drivers from here. The actual zip file with the
driver is at 3. Expand the zip somewhere locally and note the
location.
2) Put the sqlite_jni.dll from the zip into your JRE's bin directory.
The driver requires this file to be in the java library path.
3) In Eclipse with DTP 1.0 installed (preferably the final build or a
nightly build dated 110806 or later), go to the Preferences
(Window->Preferences) and select the Connectivity->Driver Definitions
page.
4) Select the "Generic JDBC" category in the Available Driver
Definitions tree and click "Add...".
5) Select "Generic JDBC Driver->Generic JDBC Driver" in the Available
Driver Templates tree. Give the new generic JDBC driver a name like
"javasqlite JDBC driver". Click OK.
6) Click "Add Jar/Zip" and select the sqlite.jar from the driver zip
you expanded in step 1. Click Open.
7) In the Properties table, select the Driver Class property and click
the "..." button. If the jar is accessible, you will see a dialog
appear with at lease one class in the list. Select
"SQLite.JDBCDriver". Click OK.
8) Also in the Properties table, select the Driver URL property and
type the following: jdbc:sqlite:/DRIVE:/dirA/dirB/dbfile
9) Click OK on the Edit Driver Definition dialog. You should see your
new driver appear in the driver list on the Driver Definitions
preference page.
10) Click OK to close the Preferences dialog.
11) If the Data Source Explorer is not open, open the
Connectivity->Data Source Explorer view from the Window->Show View
menu or open the Database Development perspective from the
Window->Open Perspective.
12) In the Data Source Explorer, right-click on the Databases category
and select New...
13) In the New Connection Profile wizard's Wizard Selection Page,
choose the SQL Model-JDBC Connection entry in the list and click Next.
14) Give your new profile a name like "SQLiteTestDB". Click Next.
15) In the "Select a driver from the drop-down" combo box, select your
new SQLite driver definition. Modify the file path in the sample URL
to match the path to your local SQLite database.
16) Click "Test Connection" to verify you can connect to your
database.
17) Click Finish to create the profile.
18) In the Data Source Explorer, right-click on the new profile and
select Connect. You should see content appear in the tree beneath the
profile. Browse through your database to view available tables and
their columns.

Related

Delete old table and create new one and prepopulate it - RoomDatabase

I am creating a simple android application in android studio with java.
I have a roomdatabase db with a table named user that has four columns
name, profession, age, description and I have prepopulated using a database that i made in sqlite studio.
Now, I want to add a column surname on the table but I want to delete all the prepopulated data and prepopulate again the table with a new database that contains also surname.
At first I thought to use auto migrations and to just add a new column. But i don't know how delete all the existing data and prepopulate again the database.
I want to delete the existing data because i want to change all the info that exists in the column description. Also as concern as the column name now it contains the fullname and in some cases is written line "name surname" and other times like "surname name" e.x "Will Smith" "Smith Will". Now I want to have the name and the surname in separate columns name and surname
Could someone recommend me something? Thank you in advance
AutoMigration will not cope with amending the data itself. Thus you will have to do that manually and thus use a destructive migration.
Here's a example (as can be seen actually undertaken)
Note this assumes no version or version 1 was assigned to the original pre-populated database and also that 1 was used for the version passed to the #Database annotation.
an SQLite database has, as part of it's header, a user_version number (offset 60 for 4 bytes). It is comparing this to the version passed to Room that determines the migration/auto migration. As is seen changing this is critical if migrating.
If developing you could just start from the changed database by making the changes to the database and the App and uninstalling the App. No need to play with version numbers.
Amend the User class by adding the new surname column. e.g.
:-
#Entity
class User {
#PrimaryKey
#NonNull
String name;
String profession;
int age;
String description;
/* ADDED FOR V2 */
String surname;
}
Compile (Ctrl + F9) and then from Android View located the generated Java and then the class that is then same as the #Database class but suffixed with _Impl.
locate the createAllTables method and then the SQL for the User table. Make a note of the SQL and the definition for the new column e.g. -surname TEXT
In SQLite Studio, run the following SQL:- ALTER TABLE user ADD COLUMN surname TEXT; where the text/code after the COLUMN key word is EXACTLY as per the SQL noted above (you can include or omit the enclosing `'s around the column name, they aren't easy to display in SO)
Look at the Data e.g. it will now be :-
note that the surname column is populated with nulls.
Edit the data accordingly. e.g. :-
Then run the following SQL PRAGMA user_version; (to check the current version)
Then run the following SQL PRAGMA user_version = 2; ( to change the version (guessing 2))
Then run the following SQL PRAGMA user_version; (to check that the version is now 2)
Quit SQLite Studio
Replace the file/asset in the project with the new database. e.g. :-
In the #Database class (NOT the generated java) :-
change the database version to 2
add the following to the the databaseBuild :-
either .fallbackToDestructiveMigrationFrom(1) if going from 1 to 2
or .fallbackToDestructiveMigration() (not as safe but more encompassing)
Run the App and e.g. :-

I converted the database file to a text file

I accidentally converted my database file to a text file. When opened, it shows that I am using the wrong encoding format. Any help would be highly appreciated.
File screenshot
I don't believe that you have because :-
Android Studio has no built-in support for browsing SQLite databases and hence why it shows as it does. It would probably look similar in NotePad.
That is there is little reason why you would open a database in Android Studio (or any other editor (unlesss it is one that supports SQLite files)).
To re-assure you, here's an SQLite database I opened in Android Studio (and goth the same message) :-
If you loaded the file into/opened the file in a tool for browsing/managing SQLite databases then I would expect that the database will be accessible.
Opening the above database in an App allows the App to output the following from the database :-
04-02 10:25:18.979 1837-1837/? D/OADB-HLPR: logDatabaseTableInformation initiated.
Database contains Table testtable created by SQL CREATE TABLE `testtable` (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT,
`timestamp` INTEGER
)
Table is testtable Column Count = 3 Row Count = 2
Columns are :- _id name timestamp
Database contains Table sqlite_sequence created by SQL CREATE TABLE sqlite_sequence(name,seq)
Table is sqlite_sequence Column Count = 2 Row Count = 1
Columns are :- name seq
logDatabaseTableInformation completed.
As you can see a lot of the information matches the screenshot.
Likewise if you accessed the database in an app then again it very much looks as though it would be as expected.
From what is shown it appears that you have a table called QuestionBank, it has a column with a type of INTEGER PRIMARY KEY AUTOINCREMENT as table sqlite_sequence exists. etc.
I say this because the first characters are SQLite format 3 as per :-
0 16 The header string: "SQLite format 3\000"
Database File Format
One such tool that is commonly used is DB Browser for SQLite.

Manually Input of data into sqlite table

How I can Manually Insert data into sqlite database table.
Manually mean insertion of data through Laptop like we are doing in MS access table etc.
Try to look for GUI clients for SQLite
SQLite Studio http://sqlitestudio.pl/
SQLite Browser http://sourceforge.net/projects/sqlitebrowser/ (http://sqlitebrowser.org/)
SQLite Admin http://sqliteadmin.orbmu2k.de/
SQLite Spy http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index
SQLite Expert http://www.sqliteexpert.com/features.html
Commercial Tools like
Navicat http://www.navicat.com/download/navicat-for-sqlite
Maestro https://www.sqlmaestro.com/products/sqlite/maestro/
Otherwise
Google chrome plugins
Firefox Addons
Yes you can insert the data in SQLite database manually by following steps.
Steps to follow:
1) Go to your sdk-tool directory . (Example - E:\android-sdk-windows\tools>)
2) Type adb shell and press enter
3) cd data
4) cd data
5) cd your package name
6) cd databases
Once you reach here then do these steps to create database and create tables then insert data into it
sqlite3 your_database_name.db;
SQLite version 3.7.7 2011-06-25 16:35:41
Enter ".help" for instructions Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE province_table (pid INTEGER PRIMARY KEY AUTOINCREMENT, pname TEXT);
sqlite> INSERT INTO province_table (pname) values ('Quebec');
sqlite> ...
sqlite> .q
.q for quiet from SQLlite and now you have database your_database_name.db.
But here in your case if you want to create the database for all mobile such like that once your application run the start database manipulation then you must to do it programmatically.

reading sqlite database using java [duplicate]

What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the ATTACH command on the SQLite 3 command line tool?
There are a few steps to see the tables in an SQLite database:
List the tables in your database:
.tables
List how the table looks:
.schema tablename
Print the entire table:
SELECT * FROM tablename;
List all of the available SQLite prompt commands:
.help
The .tables, and .schema "helper" functions don't look into ATTACHed databases: they just query the SQLITE_MASTER table for the "main" database. Consequently, if you used
ATTACH some_file.db AS my_db;
then you need to do
SELECT name FROM my_db.sqlite_master WHERE type='table';
Note that temporary tables don't show up with .tables either: you have to list sqlite_temp_master for that:
SELECT name FROM sqlite_temp_master WHERE type='table';
It appears you need to go through the sqlite_master table, like this:
SELECT * FROM dbname.sqlite_master WHERE type='table';
And then manually go through each table with a SELECT or similar to look at the rows.
The .DUMP and .SCHEMA commands doesn't appear to see the database at all.
To show all tables, use
SELECT name FROM sqlite_master WHERE type = "table"
To show all rows, I guess you can iterate through all tables and just do a SELECT * on each one. But maybe a DUMP is what you're after?
Use .help to check for available commands.
.table
This command would show all tables under your current database.
There is a command available for this on the SQLite command line:
.tables ?PATTERN? List names of tables matching a LIKE pattern
Which converts to the following SQL:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1
To list the tables you can also do:
SELECT name FROM sqlite_master
WHERE type='table';
I use this query to get it:
SELECT name FROM sqlite_master WHERE type='table'
And to use in iOS:
NSString *aStrQuery=[NSString stringWithFormat:#"SELECT name FROM sqlite_master WHERE type='table'"];
Try PRAGMA table_info(table-name);
http://www.sqlite.org/pragma.html#schema
According to the documentation, the equivalent of MySQL's SHOW TABLES; is:
The ".tables" command is similar to setting list mode then executing
the following query:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1;
However, if you are checking if a single table exists (or to get its details), see LuizGeron's answer.
As of the latest versions of SQLite 3 you can issue:
.fullschema
to see all of your create statements.
The easiest way to do this is to open the database directly and use the .dump command, rather than attaching it after invoking the SQLite 3 shell tool.
So... (assume your OS command line prompt is $) instead of $sqlite3:
sqlite3> ATTACH database.sqlite as "attached"
From your OS command line, open the database directly:
$sqlite3 database.sqlite
sqlite3> .dump
Via a union all, combine all tables into one list.
select name
from sqlite_master
where type='table'
union all
select name
from sqlite_temp_master
where type='table'
Use:
import sqlite3
TABLE_LIST_QUERY = "SELECT * FROM sqlite_master where type='table'"
Use .da to see all databases - one is called 'main'.
Tables of this database can be seen by:
SELECT distinct tbl_name from sqlite_master order by 1;
The attached databases need prefixes you chose with AS in the statement ATTACH, e.g., aa (, bb, cc...) so:
SELECT distinct tbl_name from **aa.sqlite_master** order by 1;
Note that here you get the views as well. To exclude these add:
where type = 'table'
before ' order'
Since nobody has mentioned about the official reference of SQLite, I think it may be useful to refer to it under this heading:
https://www.sqlite.org/cli.html
You can manipulate your database using the commands described in this link. Besides, if you are using Windows OS and do not know where the command shell is, that is in the SQLite's site:
https://www.sqlite.org/download.html
After downloading it, click sqlite3.exe file to initialize the SQLite command shell. When it is initialized, by default this SQLite session is using an in-memory database, not a file on disk, and so all changes will be lost when the session exits. To use a persistent disk file as the database, enter the ".open ex1.db" command immediately after the terminal window starts up.
The example above causes the database file named "ex1.db" to be opened and used, and created if it does not previously exist. You might want to use a full pathname to ensure that the file is in the directory that you think it is in. Use forward-slashes as the directory separator character. In other words use "c:/work/ex1.db", not "c:\work\ex1.db".
To see all tables in the database you have previously chosen, type the command .tables as it is said in the above link.
If you work in Windows, I think it might be useful to move this sqlite.exe file to same folder with the other Python files. In this way, the Python file writes to and the SQLite shell reads from .db files are in the same path.
The ".schema" commando will list available tables and their rows, by showing you the statement used to create said tables:
sqlite> create table_a (id int, a int, b int);
sqlite> .schema table_a
CREATE TABLE table_a (id int, a int, b int);

adf refresh mysql auto_increment "ID" not shown until query is re-executed

I have a problem very similar to this question :
Oracle ADF web browser refresh button gets old page
My application is also running on top of a MySQL database. I have a table named IncidentType which contains 2 columns :
IncidentTypeID (int, auto_increment)
Description (varchar 60)
In my web page, I can create new records and commit them to the database. However, the IncidentTypeID will not be shown until I reload the page (via a "refresh" or close then reopen the page). Essentially, not until the VO's query is executed again on the database.
If I look at the data in the database, the IncidentTypeID is correctly assigned.
I noticed the same behaviour on the ADF Business Component tester.
What would you advice to modify to force the query to be re-executed after each commit and ?
I tried the solutions in the link above, but it didn't changed the behaviour.
I'm using jDev 11.1.2.3.0
See the unsupported features and "Set Up Primary Key Generation " workaround here:
http://www.oracle.com/technetwork/developer-tools/jdev/multidatabaseapp-085183.html

Categories

Resources