Get table names and column names from SQL query String - java

I am reading a CSV file into my java program and it has an sql query in its every record. I want to parse this (Select)SQL query to find the table names and column names mentioned in those queries.
e.g. Select age,name from Employee
Result:
---- Tables: [Employee]
---- Columns: [age,name]
NOTE: I do not want to fire the queries else I would have used ResultSetMetaData

For simple SQL statements like your example above i would use some simple string methods to get the info. Example:
public static void main (String[]args) {
String sql = "Select age,name,adress,id from Employee where id = 3";
String[] columns = sql.substring(sql.indexOf("Select")+7, sql.indexOf("from")-1).split(",");
String table = sql.substring(sql.indexOf("from")+5).split(" ")[0];
System.out.println(Arrays.toString(columns));
System.out.println(table);
}

Related

DatabaseMetaData.getColumns returns columns of similar named tables

In my database I have tables "EMPLOYEE_DETAILS" and "EMPLOYEE DETAILS" with different columns for both tables. When I used the getColumns() method of the DatabaseMetaData (java.sql.DatabaseMetaData) to get the column details of the table "EMPLOYEE_DETAILS", I am getting the columns of both "EMPLOYEE_DETAILS" and "EMPLOYEE DETAILS".
I have tried this for databases Oracle, MySql and MSSQL. The result is same.
The code which I have used to call the getColumns method is given below :
String tableName = "EMPLOYEE_DETAILS";
ResultSet columnResultSet = databaseMetaData.getColumns(null, null,tableName, null);
while (columnResultSet.next()) {
System.out.println(columnResultSet.getString("COLUMN_NAME"));
System.out.println(columnType = columnResultSet.getString("TYPE_NAME"));
System.out.println(columnSize = columnResultSet.getInt("COLUMN_SIZE"));
}
Could anyone please help me to resolve this.

Java-Sqlite Truncate all Database tables

How to Truncate All Tables in Sqlite Database using Java?
I know i can do this
{
...
String table_name1 = "Delete From table_name1";
String table_name2 = "Delete From table_name2";
String table_name3 = "Delete From table_name3";
String table_name4 = "Delete From table_name4";
String table_name5 = "Delete From table_name5";
stmt.executeUpdate(table_name1);
...
}
I can execute all these Strings to do the task but it increases the Lines of Code.
Is there a way to Truncate all tables in a Database with a single command, without separately typing there names?
There's no TRUNCATE in sqlite. You can use DELETE FROM <tablename> to delete all table contents. You'll need to do that separately for each table.
However, if you're interested in removing all data, consider just deleting the database file and creating a new one.
SQLite do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop complete table and re-create it once again.
Try
{
...
String table_name1 = "DELETE FROM table_name1";
String table_name2 = "DELETE FROM table_name2";
String table_name3 = "DELETE FROM table_name3";
String table_name4 = "DELETE FROM table_name4";
String table_name5 = "DELETE FROM table_name5";
stmt.executeUpdate(table_name1);
...
}

Insert string inside another string from one index to another index in between the string

I have a SQL select query already written in java. Now i want to select few more columns. In that case i need to write column names before the index of from keyword.
Like this
Initial query-
StringBuffer query;
query = " Select name,age,dob from employee"
New query should be like this-
query = "select name , age , dob,city from employee"
For this i tried query= query.insert(indexof(dob),"city");
But i think this will overwrite from.
My question comes down to whether insert creates enough space to insert the string or it overwrites the earlier string?
Please help.
instead of getting index value of dob, get index value of from
query= query.insert(original.indexOf("from"),"city ");
Try this:-
StringBuffer query = new StringBuffer("Select name,age,dob from employee");
query.insert(query.indexOf("from"), "city ");

SQL query to select tablename

I want to get all database table names that ends with _tbl like xyz_tbl, pqr_tbl,etc..
in mysql using java.pls help me.. currently my query retreives all tablename but i jst want table names that ends with _tbl.
My code is...
public List selectTable() {
List tableNameList= new ArrayList();
try {
DatabaseMetaData dbm = c.conn.getMetaData();
String[] types = {"TABLE"};
c.rs = dbm.getTables(null, null, "%", types);
while (c.rs.next()) {
tableNameList.add(c.rs.getString("TABLE_NAME"));
}
} catch(Exception e) {
System.out.println(e.toString());
}
return tableNameList;
}
Did you try using a different table name pattern?
You can try this: -
c.rs = dbm.getTables(null, null, "%_tbl", types);
You can use mysql query
show tables from tablename like '%_tbl';
I am unable to reply to Rohit's post. his answer looks correct.
If you do to JDK documentation for DatabaseMetaData's getTables method following is the signature and documentation comment.
ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types) throws SQLException
Parameters:
catalog - a catalog name; must match the catalog name as it is stored
in the database; "" retrieves those without a catalog; null means that
the catalog name should not be used to narrow the search
schemaPattern
- a schema name pattern; must match the schema name as it is stored in the database; "" retrieves those without a schema; null means that the
schema name should not be used to narrow the search tableNamePattern -
a table name pattern; must match the table name as it is stored in the
database types - a list of table types, which must be from the list of
table types returned from getTableTypes(),to include; null returns all
types
In this case using %_tbl should work.
Use the String.endsWith() method to check if the table name ends with "_tbl".
For example inside your while loop:
while (c.rs.next())
{
String tableName = c.rs.getString("TABLE_NAME");
if(tableName.endsWith("_tbl"))
{
tableNameList.add(c.rs.getString("TABLE_NAME"));
}
}

PreparedStatement not returning ordered ResultSet

I am having some problems and I'm sure it's something stupid.
So I have a query like
SELECT name, id, xyz FROM table ORDER BY ?
then later down the road setting the ? doing a
ps.setString(1, "xyz");
I am outputting the query and the value of xyz in the console. When I loop through the ResultSet returned from the PreparedStatement the values are not in the correct order. They are in the returned order as if I had left the ORDER BY clause off. When I copy/paste the query and the value into TOAD it runs and comes back correctly.
Any ideas to why the ResultSet is not coming back in the correct order?
The database will see the query as
SELECT name, id, xyz FROM table ORDER BY 'xyz'
That is to say, order by a constant expression (the string 'xyz' in this case). Any order will satisfy that.
? is for parameters, you can't use it to insert column names. The generated statements will look something like
SELECT name, id, xyz FROM table ORDER BY 'xyz'
so that your entries are sorted by the string 'xyz', not by the content of column xyz.
Why not run:
ps.setInteger(1, 3);
Regards.
EDIT: AFAIK Oracle 10g supports it.
PreparedStatement placeholders are not intend for tablenames nor columnnames. They are only intented for actual column values.
You can however use String#format() for this, that's also the way I often do. For example:
private static final String SQL_SELECT_ORDER = "SELECT name, id, xyz FROM table ORDER BY %s";
...
public List<Data> list(boolean ascending) {
String order = ascending ? "ASC" : "DESC";
String sql = String.format(SQL_SELECT_ORDER, order);
...
Another example:
private static final String SQL_SELECT_IN = "SELECT name, id, xyz FROM table WHERE id IN (%s)";
...
public List<Data> list(Set<Long> ids) {
String placeHolders = generatePlaceHolders(ids.size()); // Should return "?,?,?..."
String sql = String.format(SQL_SELECT_IN, placeHolders);
...
DAOUtil.setValues(preparedStatement, ids.toArray());
...
The database will see the query like this
SELECT name, id, xyz FROM table ORDER BY 'xyz'
I think you should add more variable like order_field and order_direction
I assume you have a method like below and I give you an example to solve it
pulbic List<Object> getAllTableWithOrder(String order_field, String order_direction) {
String sql = "select * from table order by ? ?";
//add connection here
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1,order_field);
ps.setString(2,order_direction);
logger.info(String.valueOf(ps)); //returns something like: com.mysql.jdbc.JDBC4PreparedStatement#a0ff86: select * from table order by 'id' 'desc'
String sqlb = String.valueOf(ps);
String sqlc = sqlb.replace("'"+order_field+"'", order_field);
String sqld = sqlc.replace("'"+order_direction+"'", order_direction);
String[] normQuery = sqld.split(":");
ResultSet result = conn.createStatement().executeQuery(normQuery[1]);
while(result.next()) {
//iteration
}
}

Categories

Resources