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

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

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 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);

Mysql Insert query in Java

Im getting an sql syntax error somewhere at the end of this code line, i have tweaked it and mixed a bit with it but so far i haven't solved it.
strSQL="INSERT INTO " + tableName + " VALUES " + "(" + id + ",'" + rname + "','" + rfn + "','" + rmn + ")";
Any help appreciated!
You are missing a quote at the end
+ rmn + " )";
^---------here
But actually you should rather use Prepared Statements.
You have missed several ' signs. (not only in the end, but before and after the id)
strSQL="INSERT INTO " + tableName + " VALUES " + "('" + id + "','" + rname + "','" + rfn + "','" + rmn + "')";
Not related to the question, but strongly related to the proper creation of queries in Java:
You should avoid constructing queries with String contatenation. Instead, use PreparedStatement parameters. For example, you query would look like this:
strSQL="INSERT INTO " + tableName + " VALUES (?, ? , ? , ?)";
There is no field name specified.write like this
INSERT INTO tbl_name (col1,col2) VALUES(val1, vale2);
Check url:http://dev.mysql.com/doc/refman/5.6/en/insert.html

Is it possible to use prepared statement placeholders for LIKE?

This fails: db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE '?%'");
Because the ? is not recognized as a placeholder for a value. How should I work around this?
Put the wildcard in the variable, rather than in the statement, like:
stmt = db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE ?");
stmt.setString(1, "myterm%");
Pass your value into the CONCAT() function:
db.prepareStatement("SELECT * FROM " + table
+ " WHERE " + column
+ " LIKE CONCAT(?, '%')");
The advantage of doing it this way is the code making the call doesn't need to know that the parameter is being used with a LIKE, so you could use the same parameter value with other non-LIKE queries.
Try including the percent sign as part of the LIKE parameter:
db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE ?");
I don't like the query much. I don't think you're saving much by concatenating table and column in this way.

Java and Database Query?

Using Derby as my data base driver and tying to execute SQL query through java,
there was a error that was encounter, when tried to execute this particular query
stmt.executeQuery("insert into " + "TEST " + "values (" + dataTimeRev + ", "
+ dataType + "," + obj + ")" );
Here dataTimeRev, dataType and obj are variables with data.
The error that was stated was like this
java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.
if the column data type is VARCHAR you will have to pass the value in qoutes like 'value' for that you should do as below
String query = "insert into TEST values('"+dataTimeRev+"', '"+dataType+"','"+obj+"')";
stmt.executeQuery(query);
Verify that dataTimeRev, dataType and obj are not null and not blank.
I am not sure if Derby follows SQL syntax. But if the values are of type varchar, then it should be enclosed in single quotes ('). For example:
stmt.executeQuery("insert into " + "TEST " + "values ('" + dataTimeRev + " ', ' "
+ dataType + " ',' " + obj + " ')" );
Try this:
stmt.executeQuery("insert into TEST values ('" + dataTimeRev + "', "'+ dataType + "',"' + obj + "')" );
One of the causes of this error is trying to insert a Type that isn't a String (Date, Double, Integer e.t.c, surrounded by the single quotation mark ''
For example my table was declared like this:
String createTableStatement = "CREATE TABLE PRODUCT"+ "(product_id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
"product_name CHAR(80), "+
"price DOUBLE," +
"supplier CHAR(50))";
So I was doing:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + "'" + price + "', " + "'" + supplier +"')");
instead of:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + price + ", " + "'" + supplier +"')");

Categories

Resources