Error access to database - java

Please explain to me differents between
private boolean inUse(JDBCTemplates jdbc, BigInteger firmwareId) {
String query = "select * from references ref " +
"where ref.attr_id = 9 " +
"and ref.reference = ?";
try {
s = (String) jdbc.selectForObject(query....);
} catch (Exception e) {
log.info(e.toString());
}
return ...;
}
and
private boolean inUse(JDBCTemplates jdbc, BigInteger firmwareId) {
String query = "select * from references ref " +
"where ref.attr_id = 9 " +
"and ref.reference =" + firmwareId;
try {
s = (String) jdbc.selectForObject(query....);
} catch (Exception e) {
log.info(e.toString());
}
return ...;
}
In the second case, I get an access error to the database (jdbc.DataAccessException: Error due to access to database), and in the first case everything works.

try to modify your code this way, pay attention to the string query and the parameter:
private boolean inUse(JDBCTemplates jdbc, BigInteger firmwareId) {
String query = "select * from references ref " +
"where ref.attr_id = 9 " +
"and ref.reference ='" + firmwareId+"'";//Here might be the error
try {
s = (String) jdbc.selectForObject(query....);
} catch (Exception e) {
log.info(e.toString());
}
return ...;
}
try this and let us know if it works or not, so that we can try something else

Related

Java: Saving LocalDateTime to MySQL keeps subtracting 7 hours

I don't know why, but each time I try to save a LocalDateTime to MySQL then later try to view it, 7 hours have been subtracted from it. For example, when I put in LocalDateTime.of(2018, 6, 28, 18, 30) and then save it when I get it back out of the database, it says 2018-06-28 11:30. Now, I get that the reason it is doing this is because I live in Seattle which is in GMT-7. What I don't know is how to get it to stop doing that. I'm guessing this has a very simple solution, but I can't seem to figure it out.
--EDIT--
Here is the code I am using to save to the database.
public static int update(String tableName, String idColumnName, int id, Map<String, Object> newValues) {
String sql = "UPDATE " + tableName + "\n"
+ "SET lastUpdate = " + convertDateToDBString(LocalDateTime.now()) + ",\n"
+ "lastUpdateBy = '" + activeUser.getUsername() + "'";
for (Map.Entry<String, Object> newValue : newValues.entrySet()) {
sql += ", \n" + newValue.getKey() + " = " + convertObjectToDBString(newValue.getValue());
}
sql += "\nWHERE " + idColumnName + " = " + id + ";";
if (connected) {
try {
printSQL(sql);
return statement.executeUpdate(sql);
} catch (SQLException e) {
printError(1111, "Could not run UPDATE query", e);
}
}
return -1;
}
Here is the code I am using to draw from the database.
public static ResultSet query(String sql) {
if (connected) {
try {
printSQL(sql);
if (statement.execute(sql)) return statement.getResultSet();
} catch (SQLException e) {
printError(1110, "Could not run SELECT query", e);
}
}
return null;
}
I don't think this will really help solve the issue which is why I didn't bother adding it in the first place, but you guys are asking for it.
-- EDIT --
Here is the code for convertDateToDBString.
public static String convertDateToDBString(LocalDateTime datetime) {
String dateString = "'" + Timestamp.valueOf(datetime) + "'";
return dateString;
}

PSQLException index out of bound

I can't figure out why my PreparedStatement is throwing an error.
Here is my function:
public boolean updateMail(int id, String new_mail, boolean showMail) {
String login = "";
String toUpdate = "";
boolean ret = false;
try {
req = cnx.prepareStatement("SELECT login FROM compte WHERE id = ?");
req.setInt(1, id);
ResultSet rs = req.executeQuery();
if (rs.next()) login = rs.getString(1);
} catch (SQLException e) {
e.printStackTrace();
}
if (!getDestinataire(login).equals(new_mail))
toUpdate = ", new_mail=?";
String reqq = "UPDATE compte SET show_mail=?" + toUpdate + " WHERE id=?";
System.out.println("Dest : " + getDestinataire(login) + "\nnew_mail : " + new_mail + "\ntoUpdate : " + toUpdate
+ "\nreqq : " + reqq);
try {
req = cnx.prepareStatement(reqq);
req.setBoolean(1, showMail);
if (!getDestinataire(login).equals(new_mail)) {
req.setString(2, new_mail);
}
req.setInt(2 + (getDestinataire(login).equals(new_mail) ? 0 : 1), id);
req.executeUpdate();
ret = true;
} catch (SQLException e) {
e.printStackTrace();
}
return ret;
}
The getDestinataire() method is working well. The trace I'm printing out looks like this:
Dest : example#example.com new_mail : example2#example2.com toUpdate : ,
new_mail=? reqq : UPDATE compte SET show_mail=?, new_mail=? WHERE id=?
So basically I have 3 columns: show_mail, new_mail and id.
But I have an error at req.setString(2, new_mail);:
org.postgresql.util.PSQLException: L'indice de la colonne est hors limiteĀ : 2, nombre de colonnesĀ : 1.
I tried with and without the req.close() because I usually don't use it and it always worked great.
Also, this is the variable definition:
private Connection cnx;
private PreparedStatement req;
I already wrote a hundred database calls. Is this a stupid mistake that I'm too blind to see or is there a lib bug?

Connecting to different schemas using prepared statement

I have the following code running fine with one sql statement selectEmpShowDocs_SQL referring to schema1. In this scenario, I have hard coded the value of empID as 2 as shown in the sql below :
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
Now, I have another sql statement which is retrieving the emp_id value and instead of hardcoding the value just like I did above for empID, I want to pass the value of emp_id obtained from the following sql statement to the above sql statement. This is the statement which is referring to schema2.
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "
I am wondering is it possible to connect with two different schemas with one prepared statement? Here someone mentioned that prepared statement is bound to a specific database and in that case if it's not possible, what would be the best approach for me?
Here is the full code that works fine for me using only the SQL query referring to schema1.
public List<EmployeeDocument> getEmployeeDocument(String docId, Integer employeeID) throws DaoException
{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DataSource ds = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<EmployeeDocument> empShowDocs = new ArrayList<EmployeeDocument>();
try {
ds = jdbcTemplate.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(selectEmpShowDocs_SQL);
logger.debug("sql query :" + selectEmpShowDocs_SQL);
System.out.println(selectEmpShowDocs_SQL);
pstmt.setString(1, docId);
logger.debug("sql parameters, docId:" + docId);
rs = pstmt.executeQuery();
while(rs.next()) {
EmployeeDocument empShowDocRecord = new EmployeeDocument();
empShowDocRecord.setEmp_Content(rs.getString("emp_doc")));
empShowDocs.add(empShowDocRecord);
}
} catch(Throwable th) {
throw new DaoException(th.getMessage(), th);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch(SQLException sqe) {
sqe.printStackTrace();
}
pstmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
conn = null;
}
if (ds != null) {
ds = null;
}
}
return empShowDocs;
}
private String selectEmpShowDocs_SQL =
"SELECT " +
"emp_doc " +
"FROM " +
"schema1.emp_info " +
"WHERE " +
"doc_id = ? "+
"AND"+
"empID = 2";
private String selectEmpIDSQL =
"SELECT " +
"emp_id " +
"FROM " +
"schema2.emp_id " +
"WHERE " +
"company_id = 435 "

Java Database and ResultSet

First post here, so I hope I get the etiquette right.
Working on a project for a programming course, where we've been given certain parameters that make things a little awkward (because there are better ways to do it I know).
I have a database created, and populated with data, I can get the data I need from it, but the way I'm doing it is clunky and rubbish. So I'm looking for a better way.
The two classes I'm dealing with at this time are StockData.class and CheckStock.class.
StockData.class is the database handler...
in which I have the following:
public static String getPrice(String key) {
try {
ResultSet res = stmt.executeQuery("SELECT * FROM StockDB WHERE stockID = '" + key + "'");
if (res.next()) { // there is a result
return res.getString(3);
} else {
return null;
}
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
and
public static ResultSet getID()
{
try
{
ResultSet keyList = stmt.executeQuery("SELECT stockID FROM StockDB");
{
return keyList;
}
}
catch (SQLException e)
{
System.out.println(e);
return null;
}
(There are other similar ones for each column)
I'm calling these methods from CheckStock with the following:
key = "11";
debug.append(" " + newline);
debug.append(" " + StockData.getName(key));
debug.append(" " + StockData.getPrice(key));
debug.append(" " + StockData.getQuantity(key));
As you can see I'm hand typing my stockID - which is a string.. which doesn't make the system expandable (I'd have to add in a whole new set of keys by hand for any new items.
In order to use the Database to supply the keys I had tried to use the following
ResultSet stockIDList = StockData.getID();
while (stockIDList.next())
{
key = (stockIDList.getNString(1));
debug.append(" " + StockData.getName(key));
debug.append(" " + StockData.getPrice(key));
debug.append(" " + StockData.getQuantity(key));
}
But that spits out all sorts of SQL errors.
I'm assuming I'm missing something very simple, or that there's a much better way of doing it.
I've been trying to get my head around this little problem all day with the help of an internet and the oracle pages on ResultSet but I can't for the life of me work out why it's not working.
Thank you in advance of any help.
Myranda
I have (through trial and error) found a work around.
From what I could see of search results I should have been using final statments to close out the queries, but I couldn't seem to get them to fit without netBeans throwing exclamation marks all over the place...
So I used an individual statment name for each field that I was querying...
public static double getPrice(String key) {
try {
Statement stmtPrice;
stmtPrice = connection.createStatement();
ResultSet res = stmtPrice.executeQuery("SELECT * FROM StockDB WHERE stockID = '" + key + "'");
if (res.next()) {
return res.getDouble(3);
} else {
return 0;
}
} catch (SQLException e) {
System.out.println(e);
return 0;
}
}
public static int getQuantity(String key) {
try {
Statement stmtQty;
stmtQty = connection.createStatement();
ResultSet res = stmtQty.executeQuery("SELECT * FROM StockDB WHERE stockID = '" + key + "'");
if (res.next()) {
return res.getInt(4);
} else {
return 0;
}
} catch (SQLException e) {
System.out.println(e);
return 0;
}
}
Then this was called using the following
ResultSet stockIDList = StockData.getID();
while (stockIDList.next())
{
key = (stockIDList.getString(1));
stockID.append(" " + key + newline);
stockDescription.append(" " + StockData.getName(key) + newline);
stockPrice.append(" " + StockData.getPrice(key) + newline);
stockQuantity.append(" " + StockData.getQuantity(key) + newline);
double price = StockData.getPrice(key);
int quantity = StockData.getQuantity(key);
double total = price * quantity;
String stringTotal = String.valueOf(total);
stockTotalValue.append(" " + stringTotal + newline);
}
No doubt someone will be horrified by the clunky code I've used, but it seems to be doing the job, so for now I'll take clunky over non-functional.
Thank you all for your time.
Myranda

Getting SQL error 1078 Before start of result set in Java program [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
I have a Java method that is supposed to get column values from one MySQL row and create a string with the values. When run, it generates a SQL error 1078 "Before start of result set."
Here is the the class in which the error is occuring (Problem is in listPosesInSection method:
/** Class used to access the database */
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class YogaDatabaseAccess {
String dbUrl = "jdbc:mysql://localhost/yoga";
private Connection connection;
private ResultSet rset;
private ResultSetMetaData rsMetaData;
private Statement statement;
private PreparedStatement pStatementAll = null;
private PreparedStatement pStatementPartial = null;
// Strings for queries and updates
String strListPosesNotPrimary;
String strInsertNewClass;
String strInsertNewSection;
String strInsertNewPose;
String strUpdateClass;
String strUpdateSection;
String strUpdatePose;
String strArrangePoseOrder;
private String[] poseArray;
// Constructor
YogaDatabaseAccess() {
connectToDatabase();
}
// Method that connects to database
private void connectToDatabase() {
try {
connection = DriverManager.getConnection(dbUrl, "Kyle", "Kullerstrand#2");
System.out.println("Database connected");
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
// Query that returns lists to be used with combo boxes
public String listForBoxes(String listName) {
// List to be returned
String strList = "";
// Determine name of the database table for this list
String listTableName;
if (listName == "pose")
listTableName = listName + "s";
else if (listName == "class")
listTableName = listName + "es";
else
listTableName = listName;
// Determine the database column name for this list
String listColumnName = listName + "_name";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT " + listColumnName + " FROM " + listTableName +
" ORDER BY " + listColumnName);
while (rset.next()){
strList = strList + rset.getString(listColumnName) + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of primary poses for a section
public String listPrimaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE primarily_suitable_for = '" + sectionName +
"' OR primarily_suitable_for = 'Anything' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of secondary poses for a section
public String listSecondaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE sometimes_suitable_for = '" + sectionName + "' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns the poses within a specific section
public String listPosesInSection(String tableName, String sectionName) {
String strList;
StringBuilder strBuilderList = new StringBuilder("");
// Run the query
try {
statement = connection.createStatement();
// Query will collect all columns from one specific row
rset = statement.executeQuery("SELECT * FROM " + tableName + " WHERE " + tableName + "_name = '" + sectionName + "'");
while (rset.next()) {
for (int i = 2; i <= countColumnsInTable(tableName); i++) // First value (0) is always null, skip section name (1)
if (rset.getString(i) != null) // If column has a value
strBuilderList.append(rset.getString(i) + "\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
strList = strBuilderList.toString();
return strList.replaceAll(", $",""); // Strips off the trailing comma
}
// Insert statement that inserts a new class into the classes table
public void insertNewClass(String className) {
/** String insert = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
System.out.println("About to create the prepared statement");
// Run the insert
try {
pStatement = connection.prepareStatement(insert);
// statement.execute("INSERT IGNORE INTO poses VALUES ('" + poseName + "', '" + suitableFor + "', '" + suitableForSometimes + "')");
pStatement.setString(1, poseName);
pStatement.setString(2, suitableFor);
pStatement.setString(3, suitableForSometimes);
System.out.println("Created the prepared statement");
// execute query, and return number of rows created
pStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} */
}
// Insert statement that inserts a new pose into poses table
public void insertNewPose(String poseName, String suitableFor, String suitableForSometimes) {
String insertAll = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
String insertPartial = "INSERT INTO poses (pose_name, primarily_suitable_for) values(?, ?)";
// Run the insert
try {
if (suitableForSometimes == "NULL") { // Insert statement contains a null value for sometimes suitable column
pStatementPartial = connection.prepareStatement(insertPartial);
pStatementPartial.setString(1, poseName);
pStatementPartial.setString(2, suitableFor);
pStatementPartial.executeUpdate();
} else { // Insert statement contains values for all three columns
pStatementAll = connection.prepareStatement(insertAll);
pStatementAll.setString(1, poseName);
pStatementAll.setString(2, suitableFor);
pStatementAll.setString(3, suitableForSometimes);
pStatementAll.executeUpdate();
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "This pose already exists.");
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Insert statement that inserts a new section into warmup, work or restore sections
public void insertNewSection(String sectionType, String sectionName, ArrayList<String> poses) {
System.out.println("insertNewSection method was called");
int maxColumns = countColumnsInTable(sectionType);
poseArray = new String[poses.size()];
poseArray = poses.toArray(poseArray);
if (poseArray.length == 0)
JOptionPane.showMessageDialog(null, "There are no poses in this section. Please add poses.");
// Create a list of columns of the table for the INSERT statement
StringBuilder columns = new StringBuilder(sectionType + "_name");
for (int c = 1; c < maxColumns; c++)
columns.append(", pose_" + c);
// Create a string list of poses, separated by commas, from the array
StringBuilder values = new StringBuilder();
values.append("'" + poseArray[0] + "'");
for (int v = 1; v < poseArray.length - 1; v++)
values.append(", '" + poseArray[v] + "'");
// make sure query uses correct number of columns by padding the query with NULL
for (int i = poseArray.length; i < maxColumns; i++)
values.append(", NULL");
String posesToAddToSection = values.toString();
// The string containing the entire insert statement
String insert = "INSERT INTO " + sectionType + " (" + columns + ") VALUES ('" + sectionName + "', " + posesToAddToSection + ")";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(insert);
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "An error in the yoga design program has occurred. SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Statement that deletes rows from tables
public void deleteRow(String tableName, String columnName, String rowName) {
String delete = "DELETE FROM " + tableName + " WHERE " + columnName + " = '" + rowName + "'";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(delete);
System.out.println("Delete statement was run on Java's end.");
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "Sorry, something went wrong: SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method for getting the number of columns in a table using metadata
public int countColumnsInTable(String sectionType) {
int count = 16;
try {
// System.out.println(sectionType);
statement = connection.createStatement();
rset = statement.executeQuery("SELECT * FROM " + sectionType);
rsMetaData = rset.getMetaData();
count = rsMetaData.getColumnCount();
// System.out.println("Column count is " + count);
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
// Close the database and release resources
public void closeDatabase() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And here is the beginning of the error list:
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at YogaDatabaseAccess.listPosesInSection(YogaDatabaseAccess.java:125)
at YogaSectionDesigner$5.actionPerformed(YogaSectionDesigner.java:229)
May be you can check this out:
ResultSet exception - before start of result set
Had the same Problem. Solved it that way.

Categories

Resources