Database Java Bean SQL Statement - java

In my database bean I have a section of code which is below :
public Integer getTotalOrgPoints() {
try {
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
totalOrgPoints = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return totalOrgPoints;
}
For the statement QUERY_TOTAL_ORG_SCORE if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = 1
It will return the value for that organisation but if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = ?
I get nothing does anyone know why this is happening for me?.

Add this line to bind values for prepared statement before executequery
stmt.setInt(1, 1);
Modified:-
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();

Related

Syntax for SQL statement using mysql database

public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}

Prepared statement execute query error (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();

Java ResultSet Column count is always 1

I want to show the Column numbers of a table but it always shows the number 1. I have written the code below:
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql;
sql = "SELECT count(*) FROM information_schema.columns WHERE
table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql)) {
int columCount = rs.getMetaData().getColumnCount();
System.out.println("Column number is: "+columCount);
}
stmt.close();
con.close();
Where is the error ?
First, you haven't needed Class.forName to load your JDBC drivers in a long time. Second, you are selecting a value but you are reading metadata. Third, when using try-with-resources you don't need explicit close calls (and your Connection should be closed in a finally, for example). Finally, use PreparedStatement and bind parameters. Like,
java.sql.Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "SELECT count(*) FROM information_schema.columns WHERE table_name=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, "my_b");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
} else {
System.out.println("No rows");
}
}
} finally {
con.close();
}
You are not retrieving the result of the query, instead you are asking the result set metadata how many columns the result set has. And as your query only produce a single column (ie COUNT(*)), the result of ResultSetMetaData.getColumnCount() is 1, and that value is correct.
If you want to get the result of the query, you need to get it from the result set:
try (ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
int columnsNumber = rs.getInt(1);
System.out.println("Column number is: "+columnsNumber );
}
}
The problem is that ResultSet.getColumnCount returns the number of columns in the query's result set, not the number of columns in a table.
If you are trying to get a count of columns on a table, the query you have is correct. You just need to retrieve the result of the query, rather than its metadata.
String sql = "SELECT count(*) FROM information_schema.columns WHERE table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql));
rs.next();
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
}
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'database_name' AND table_name = 'table_name'"
try (
ResultSet rs = stmt.executeQuery(sql)) {
//int columCount = rs.getMetaData().getColumnCount();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
System.out.println("Column number is: "+columnsNumber );
}
stmt.close();
con.close();
Try SELECT * FROM information_schema.columns WHERE table_name=\"my_b\"
Just omit the count(*) since this returns a single result, while you are looking for all columns.

How to retrieve values from SQL when ID is in array form

The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code

Working with a ResultSet

I am trying to get a count from a particular table in my derby database, but when I run the code I keep getting Invalid operation at current cursor position
public int getNumUsers(){
ResultSet rs = null;
int size = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from USERS");
while(rs.next()){
size = rs.getInt("COUNT");
}
stmt.close();
} catch (SQLException sqe) {
sqe.printStackTrace();
}
return size;
}
Change your query to
select count(*) As COUNT from USERS
or change your function call to
rs.getInt(1);
give an alias to count(*) in your select statement. in mysql we use as to give alias name.I dunno about derby though, but think it'd be similar.
rs = stmt.executeQuery("select count(*) as count from USERS");
while(rs.next()){
size = rs.getInt("count");
}

Categories

Resources