In my Android database, I have number of tables. Among these tables, some contain similar names starting from "List_". For an example, there are tables like "List_A", "List_B", "List_C" etc. How can I get the list of all tables which starts from the word "List_" using code?
This should do the trick :)
SELECT *
FROM dbname.sqlite_master
WHERE type='table'
AND name LIKE 'List_%'
try this way
public void grabTables() {
Cursor cur = this.db.rawQuery("SELECT * FROM sqlite_master where name like 'List_%'", new String[0]);
cur.moveToFirst();
String tableName;
while (cur.getPosition() < cur.getCount()) {
tableName = cur.getString(cur.getColumnIndex("name"));
System.out.println("Table Name = " + tableName);
cur.moveToNext();
}
cur.close();
}
Related
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.
This is a native create statement for some unknown database carrier
String createStatement = "CREATE TABLE test_database.test_table " +
"AS " +
"( " +
"var1, " +
"var2 " +
") " +
"; "
);
I need to parse this String test_database.test_table
I don't know in advance what SQL flavor this CREATE statement is. If I knew that, I would simply use something like
String table = createStatement.split(" ")[2];
But the above solution might not work in all databases. What if some database allows for blanks in table name? So I have to use Hibernate.
How?
In general, I don't think you can do this without certain assumptions or considering each and every SQL dialect you want to support.
Hibernate itself supportes a number of SQL dialects and you can infer a lot of things from the used dialect. However, org.hibernate.dialect.Dialect does not provide enough information for parse all the possible native CREATE TABLE statements in the selected dialect.
I don't think that Hibernate can take care of all situations especially when dealing with something like Transact-SQL or CREATE GLOBAL TEMPORARY TABLE or even CREATE TEMPORARY TABLESPACE and then you have the AS, AS SELECT, and even PARALLEL COMPRESS AS SELECT after the table name to consider.
As an alternative however you can create a method which can retrieve the Table Name from a supplied CREATE TABLE SQL string which I believe will cover most (if not all) of these issues. Below is such a method:
public String getTableNameFromCreate(final String sqlString) {
// Always rememeber...we're only trying to get the table
// name from the SQL String. We really don't care anything
// about the rest of the SQL string.
String tableName;
String wrkStrg = sqlString.replace("[", "").replace("]", "").trim();
// Is "CREATE TABLE" only
if (wrkStrg.startsWith("CREATE TABLE ")) {
wrkStrg = wrkStrg .substring(13).trim();
}
else if (wrkStrg.startsWith("CREATE GLOBAL TEMPORARY TABLE ")) {
wrkStrg = wrkStrg .substring(30).trim();
}
else if (wrkStrg.startsWith("CREATE TEMPORARY TABLESPACE ")) {
wrkStrg = wrkStrg .substring(28).trim();
}
// Is it Create Table ... AS, AS SELECT, PARALLEL COMPRESS AS,
// or PARALLEL COMPRESS AS SELECT?
if (wrkStrg.toUpperCase().contains(" PARALLEL COMPRESS ")) {
wrkStrg = wrkStrg.replace(" parallel compress ", " PARALLEL COMPRESS ");
tableName = wrkStrg.substring(0, wrkStrg.indexOf(" PARALLEL COMPRESS ")).trim();
}
else if (wrkStrg.toUpperCase().contains(" AS ")) {
wrkStrg = wrkStrg.replace(" as ", " AS ");
tableName = wrkStrg.substring(0, wrkStrg.indexOf(" AS ")).trim();
}
// Nope...none of that in the SQL String.
else {
tableName = wrkStrg.substring(0, wrkStrg.indexOf("(")).trim();
}
// return but remove quotes first if any...
return tableName.replace("\"","").replace("'", "");
}
If the database name is attached to the table name as in your example (test_database.test_table) then of course you will need to further parse off the actual table name.
I think the title is clearly. There is a sqlite app in android. The app is when starts, it's creates a database and tables. But the tables, columns, types, column count absolutely not specific. So, I need to create a perfect dynamic structure. I will take columns, tables, types and anything of about database from a xml. That is the point, the xml...
String query = "CREATE TABLE IF NOT EXISTS a(" + col_parameter1 +" " type_paramater1+","+ ... col_paramaterN + " " + type_parameterN +")" ;
I dont know how many creates table, how many colunms. I do try too way but all of them not perfect.
Try this. I think it will help you
class Column {
String name;
String type;
}
public class Main{
//Fill colums with data read from xml
public String createTableQuery(List<Column> colums){
StringBuffer query = new StringBuffer();
query.append("CREATE TABLE IF NOT EXISTS a(") ;
for(int i = 0; i < colums.size(); i++){
Column col = colums.get(i);
query.append(" " + col.name + " " +col.type + ", ");
}
query.append(")");
return query.toString();
}
}
I have tried this code
Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'",null);
c.moveToFirst();
while(!c.isAfterLast()){
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0),
Toast.LENGTH_LONG).show();
}
But it throws the error:
"android.database.sqlite.SQLiteException: no such table: sqlite_master(code 1):, while
compiling: SELECT name FROM sqlite_master WHERE type='table'"
How to fetch all the table names?
Checked, tested and functioning. Try this code:
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show();
c.moveToNext();
}
}
I am assuming, at some point down the line, you will to grab a list of the table names to display in perhaps a ListView or something. Not just show a Toast.
Untested code. Just what came at the top of my mind. Do test before using it in a production app. ;-)
In that event, consider the following changes to the code posted above:
ArrayList<String> arrTblNames = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
Change your sql string to this one:
"SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata' order by name"
To get table name with list of all column of that table
public void getDatabaseStructure(SQLiteDatabase db) {
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table'", null);
ArrayList<String[]> result = new ArrayList<String[]>();
int i = 0;
result.add(c.getColumnNames());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String[] temp = new String[c.getColumnCount()];
for (i = 0; i < temp.length; i++) {
temp[i] = c.getString(i);
System.out.println("TABLE - "+temp[i]);
Cursor c1 = db.rawQuery(
"SELECT * FROM "+temp[i], null);
c1.moveToFirst();
String[] COLUMNS = c1.getColumnNames();
for(int j=0;j<COLUMNS.length;j++){
c1.move(j);
System.out.println(" COLUMN - "+COLUMNS[j]);
}
}
result.add(temp);
}
}
Try adding the schema before the table
schema.sqlite_master
From SQL FAQ
If you are running the sqlite3 command-line access program you can type ".tables" to get a list of all tables. Or you can type ".schema" to see the complete database schema including all tables and indices. Either of these commands can be followed by a LIKE pattern that will restrict the tables that are displayed.
From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a SELECT on a special table named "SQLITE_MASTER". Every SQLite database has an SQLITE_MASTER table that defines the schema for the database. The SQLITE_MASTER table looks like this:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);
Try this:
SELECT name FROM sqlite_master WHERE type = "table";
I tested Siddharth Lele answer with Kotlin and Room, and it works as well.
The same code but using Kotlin and Room is something like that:
val cursor = roomDatabaseInstance.query(SimpleSQLiteQuery("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('android_metadata', 'sqlite_sequence', 'room_master_table')"))
val tableNames = arrayListOf<String>()
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
tableNames.add(cursor.getString(0))
cursor.moveToNext()
}
}
I have a database table with multiple columns
I use custom List<> and populate it from database
What i want to do is filter what will go into the list from database depending on user input
for example if i had a table like this:
name|phone|date|address
User can specify any filter(by name, by phone, by date... or all of it) and only items that matches all criteria will go into the list
Is there a way to do this?
Method that returns all items from database
public List<MoviesDatabaseEntry> getAllMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
MoviesDatabaseEntry list = new MoviesDatabaseEntry();
list.set_id(Integer.parseInt(cursor.getString(0)));
list.set_title(cursor.getString(1));
list.set_runtime(cursor.getString(2));
list.set_rating(cursor.getDouble(3));
list.set_genres(cursor.getString(4));
list.set_type(cursor.getString(5));
list.set_lang(cursor.getString(6));
list.set_poster(cursor.getString(7));
list.set_url(cursor.getString(8));
list.set_director(cursor.getString(9));
list.set_actors(cursor.getString(10));
list.set_plot(cursor.getString(11));
list.set_year(cursor.getInt(12));
list.set_country(cursor.getString(13));
list.set_date(cursor.getInt(14));
// Adding to list
lists.add(list);
} while (cursor.moveToNext());
}
// return list
db.close();
cursor.close();
return lists;
}
You can filter the entries you get in the SQL query you are building in this line:
String selectQuery = "SELECT * FROM " + table;
To filter the dataset your retrieve, you would add a WHERE clause to it. When you would, for example, only want those entries where the rating is over 3, you would change this to:
String selectQuery = "SELECT * FROM " + table + " WHERE rating > 3";
SQL is a very powerful language which offers a lot of possibilities. It's an essential skill when you work with relational databases. When you want to learn it, I can recommend you the interactive tutorial website http://sqlzoo.net/
You have to change your database query for getting specific data from the query.
You have one function that returns all rows from database like so: getAllMovies(String table)
Here you are using:
String selectQuery = "SELECT * FROM " + table;
Make a new function like this:
public List<MoviesDatabaseEntry> getSelectedMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { <your row names> },
**check condition(as string)**, null,
null, null, null, null);
...
}
Now just call this function when required with your specific query string
Make as many functions as you want!