Preview static strings in Android Studio? - java

I'm having some problems reading what the actual SQL query is behind all this java code. This is just an example, though.
Is there an easy way to get the actual string behind this in Android Studio? It's really just a hard-coded string, after all.
private static final String CREATE_TABLE_ARTICLES = "CREATE TABLE " +
TABLE_ARTICLES + "(" + ARTICLES_KEY_ID + " INTEGER PRIMARY KEY, " +
ARTICLES_KEY_NAME + " TEXT, "+ ARTICLES_KEY_PERCENT_FAT + " INTEGER, " +
ARTICLES_KEY_PRICE + " INTEGER, " +
ARTICLES_KEY_SALES_START + " TEXT, " + ARTICLES_KEY_SALES_STOP + " TEXT, " +
ARTICLES_KEY_VOLUME + " INTEGER, " + ARTICLES_KEY_PRODUCT_GROUP + " TEXT)";

I usually use Log.i or Log.d to print out SQL commands to the console for better readability. If you make the string public (temporarily) you can call it from your main activity.
Log.i("SQLTEST", "create_table command: " + YourClass.CREATE_TABLE_ARTICLES);

Related

How do I access and display specific records in a MySQL relational-database using JDBC/Java?

I have a project-management-system that used to read data from text-files, but is now being changed to read data from a database.
I am trying to figure out how to display specific information in different tables based on the project number in the projects table.
All of the tables in my database are related to this project table.
A Visual Presentation of My Database
ERD for my database:
My Problem
Neatly display all the information for for project.
What I am trying to figure out is, how do I get a specific record in one table, based on the foreign-keys in my projects table?
For example, if a project has an architect with the architect_name "Bryan" , then how do I display the architect details for just "Bryan"?
My Code for my displayAll method
public static void viewAllProjects() {
// Calling the 'connectionAttempt' method to connect to the 'ebookstore' database.
Connection connection = connectionAttempt();
PreparedStatement ps;
// Using a try- catch block to print the data for a specific record in the 'books' table.
try {
// Creating and using a normal statement to select the specific record in the database.
Statement statement = connection.createStatement();
// SQL select statement
String q = "select * from architect\n" +
"union all\n" +
"select * from contractor\n" +
"union all\n" +
"select * from customer" +
"union all\n" +
"select * from shopping_basket\n" +
"union all\n" +
"select * from projects\n" +
"union all\n" +
"select * from building_info";
ResultSet rs = statement.executeQuery(q); // Executing statement
// Printing ResultSet
if (rs.next()) {
String projectDetails = "\nProject Number: " + rs.getString("project_number") + "\n" +
"Project Name: " + rs.getString("project_name") + "\n" +
"Type of building: " + rs.getString("HERE") + "\n" +
"ERF Number: " + rs.getString("HERE") + "\n" +
"Physical Address: " + rs.getString("physical_address") + "\n" +
"Total fee charged for project: " + rs.getString("HERE") + "\n" +
"Total amount already paid: " + rs.getString("HERE") + "\n" +
"Deadline of the project: " + rs.getString("deadline") + "\n" +
"Project Finalised: " + rs.getString("finalised") + "\n" +
"\nArchitect Name: " + rs.getString("architect_name") + "\n" +
"Architect Telephone Number: " + rs.getString("id") + "\n" +
"Architect Email-Address: " + rs.getString("id") + "\n" +
"Architect Physical Address: " + rs.getString("id") + "\n" +
"\nContractor Name: " + rs.getString("contractor_name") + "\n" +
"Contractor Telephone Number: " + rs.getString("id") + "\n" +
"Contractor Email-Address: " + rs.getString("id") + "\n" +
"Contractor Physical Address: " + rs.getString("id") + "\n" +
"\nCustomer Name: " + rs.getString("HERE") + "\n" +
"Customer Telephone Number: " + rs.getString("HERE") + "\n" +
"Customer Email-Address: " + rs.getString("HERE") + "\n" +
"Customer Physical Address: " + rs.getString("HERE") + "\n" +
"----------------------------------\n";
System.out.println(projectDetails);
} else {
System.out.println("Record Not Found...");
}
connection.close();
} catch (Exception e) {
System.out.println(e);
}
}
My code for the connectionAttempt method works, as I used it before.
Please let me know if there are any other details I can provide.
This project is not going to work out until you learn SQL. Once you do, you'd know that UNIONing together every row in the entire database is a crazy way to work. This attempts to pump over all data in your database in an incredibly inefficient way.
If a project has an architect with the architect_name "Bryan" , then I how do display the architect details for just "Bryan".
An SQL statement along the lines of SELECT * FROM architect WHERE architect_name = ? (make that your PreparedStatement), then use ps.setString(1, "The name of the architect goes here"); to set the query parameters, then run it, and voila.
You may want to 'marshal' the returned data into a specialized java object that represents exactly the data returned, because working with some java class is a lot simpler than having to run a ton of rs.getString... style statements. more on that later.
If you want all projects that brian made, then there's no way to tell unless you explain to us how your database is designed. But it'll look something along the lines of:
SELECT p.* FROM projects p
INNER JOIN architect a ON p.architect = a.unid
WHERE a.architect_name = ?
You need to know about SQL - search the web for any SQL tutorial.
You also need to interact with it from the java side. You're currently doing raw JDBC - not recommended. Read up on JDBI or if you prefer, JOOQ. These also make that marshalling thing a lot simpler.

Sqlite- Show results in desired order

I have created a sqlite table with two columns -Code and Name and stored data in it. User is provided a searchview to enter code or name and the app show results accordingly.
I am using below query to fetch results-
cursor = db.query(TABLE_SEARCH, columns, COLUMN_CODE + " LIKE '" +
searchText + "%' or " + COLUMN_ NAME + " LIKE '%" + searchText + "%'", null, null, null, null)
But the problem is that doesn’t show results in desired order.
I want to show results in below order-
1.On top show results with the Code exactly matching with the searched text.
2.Below that show results with the Name exactly matching with searched text.
3.Below that show results with the Code starting with the searched text.
4.Below that show results with the Name containing the searched text.
If I run multiple sqlite queries it makes the search slow.How can I accomplish my requirement in best way without affecting performance?
The last argument of the query() method is the ORDER BY clause.
Try conditional sorting:
cursor = db.query(
TABLE_SEARCH,
columns,
COLUMN_CODE + " LIKE '" + searchText + "%' OR " +
COLUMN_ NAME + " LIKE '%" + searchText + "%'",
null,
null,
null,
"CASE " +
"WHEN " + COLUMN_CODE + " = '" + searchText + "' THEN 1 " +
"WHEN " + COLUMN_ NAME + " = '" + searchText + "' THEN 2 " +
"WHEN " + COLUMN_CODE + " LIKE '" + searchText + "%' THEN 3 " +
"WHEN " + COLUMN_ NAME + " LIKE '%" + searchText + "%' THEN 4 " +
"END, " + COLUMN_CODE + ", " + COLUMN_ NAME
)
For better performance, you should set indexes for the columns COLUMN_CODE and COLUMN_ NAME.
Also by concatenating so many strings you risk sql injection.
I hope you do check if searchText contains single quotes and change them to double single quotes, like:
searchText = searchText.replace("'", "''");

SQLite in java - I have only one table that seems too big?

I have an app that allows users to store an int value for 50 different symptoms once per day. So in my SQLite db, my primary key is the symptom and the date (see below).
String CREATE_TABLE_SYMPTOM = "CREATE TABLE " + Symptom.TABLE + "("
+ Symptom.KEY_Symptom + " INTEGER NOT NULL , "
+ Symptom.KEY_date + " INTEGER NOT NULL , "
+ Symptom.KEY_level + " INTEGER , "
+ "PRIMARY KEY ( " + Symptom.KEY_Symptom + " , " + Symptom.KEY_date + " ))";
My table with have 50 entries per day which is alot.
Is there a more efficient way of breaking up this table so I won't have so many entries? I

Sqlite Android Optimization

I have an application that works well. But I suspect that I can improve it if I optimize queries to the database. And I need suggestions.
This is part of my "select query":
private static final String SELECT = "SELECT " +
"dz.first_id AS first_id, " +
"dz._id AS _id, " +
"dz.att1 AS att1, " +
"dz.att2 AS att2, " +
"dz.att3 AS att3, " +
"dz.att4 AS att4, " +
"dz.att5 AS att5, " +
"d.var1 AS var1, " +
"d.name AS name, " +
"d.last_update AS last_update, " +
"d.image_url AS image_url, " +
"d.image_highlighted_url AS image_highlighted_url, " +
"d.var2 AS var2, " +
"d.type AS type, " +
"d.state AS state, " +
"d.sync AS sync, " +
"d.var3 AS var3 " +
"FROM table1 dz INNER JOIN table2 d " +
"ON d._id = dz.first_id ";
Cursor result = conn.rawQuery(SELECT, null);
*table1 and table2 have simple creation: only one _id integer PRIMARY KEY AUTOINCREMENT NOT NULL
It is useful to use views? Any other suggestion?
Thanks.
This query looks as cut and dry and they can get, I think your options are really either to see if you can somehow leave some unnecessary columns out of your select or alternatively to see that both dz.first_id and d._id have indexes setup. Perhaps add a index to dz with the following
CREATE INDEX index1 ON table1 (first_id);

How to put a real values in SQL query using postgreSQL?

I have some problems with an application developed in Java that uses postgreSQL as a DB. I managed to make a dummy query as follows:
String sql = "INSERT INTO voicemessages (UNIQUEID,MSGNM,DIR,CONTEXT,MACROCONTEXT,CALLERID, ORIGTIME,DURATION, FLAG,MAILBOXUSER,MAILBOXCONTEXT,RECORDING, LABEL, read ) "
+ "VALUES (1, 1, 'dir/dir1/msgs', 'message', 'message', '6001', '15/01/2015 13:31:25', '1:32', 'flag', 'Georgi Georgiev', 'Georgi Georgiev', '12314124', 'some label', false);";
And it works perfect when I execute the statement. A row in the DB is created and I am able to display the data using:
SELECT * FROM voicemessages;
The problem is when I create my own VoiceMail class and when I create an object from this type and put in the query the getters and setters for this object I receive some kind of an error:
org.postgresql.util.PSQLException: ERROR: column "dir" does not exist Hint:There is a column named "dir" in table "voicemessages", but it cannot be referenced from this part of the query.Position: 169
I am trying to insert a row by using and executing this:
String sql = "INSERT INTO voicemessages (UNIQUEID,MSGNM,DIR,CONTEXT,MACROCONTEXT,CALLERID, ORIGTIME,DURATION, FLAG,MAILBOXUSER,MAILBOXCONTEXT,RECORDING, LABEL, read ) "
+ "VALUES (" + message01.getUniqueId() + ", " + message01.getMessageNumber() + ", " + message01.getDirectory() + ", " + message01.getContext() + ", " + message01.getMacroContext() + ", " + message01.getCallerId() + ", " +message01.getOrigTime() + ", " + message01.getDuration() + ", " + message01.getFlag() + ", " + message01.getMailboxUser() + ", " +message01.getMailboxContext() + ", " + message01.getRecording() + ", " + message01.getLabel() + ", " + message01.getRead()+ ");"+" ";
Any help or suggestion is appreciated.
Thank you in advance!
Do not use Direct values use parameters for safety, What happens is that the SQL statement you pass is parsed to prepare and compiled by the database. So by sending the actual SQL separately from the parameters, you limit the risk of SQL injection

Categories

Resources