I made a java app on my local machine which is connecting to a remote MySQL database, when I run on localhost it works OK, but on the remote connection after a few seconds without interaction it is losing the connection and brings
No operation allowed after connection closed.
and
com.mysql.jdbc.exceptions.jdbc4.MySQL.NonTransientConnectionException:No operation allowed after connection closed.
I have tried to remove con.close from my code but still the same.
How do I keep the connection alive until I close the app?
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
// TODO add your handling code here:
String stkidreq = txtserchreq.getText();
String pool = lblpool.getText();
String dform = ((JTextField) jdaterfrom.getDateEditor().getUiComponent()).getText();
String dto = ((JTextField) jdaterto.getDateEditor().getUiComponent()).getText();
String rstatus = cmbstatus.getSelectedItem().toString();
String exdate = ((JTextField) jdaterfrom.getDateEditor().getUiComponent()).getText();
((DefaultTableModel) tblreq.getModel()).setRowCount(0);
DefaultTableModel model = (DefaultTableModel) tblreq.getModel();
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn2 = DriverManager.getConnection("jdbc:mysql://so /so n so", "so so", "");
Statement st = conn2.createStatement();
String query = " select r.request_id, r.shareholder_id, s.username, s.shareholder_fname, s.shareholder_lname, s.shareholder_phone, r.request_date, r.request_amount, r.pool, r.notes, r.req_status from requests r, shareholder s, saving_pool p where r.shareholder_id = '" + stkidreq + "' and s.shareholder_id = '" + stkidreq + "' and p.Pool_name = '" + pool + "' and s.pool = '" + pool + "' and s.shareholder_id = r.shareholder_id and (r.request_date between '" + dform + "' and '" + dto + "') and r.req_status = '" + rstatus + "' order by r.request_date asc ";
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String request_id = rs.getString("request_id");
String shareholder_id = rs.getString("shareholder_id");
String username = rs.getString("username");
String shareholder_fname = rs.getString("shareholder_fname");
String shareholder_lname = rs.getString("shareholder_lname");
String shareholder_phone = rs.getString("shareholder_phone");
String request_date = rs.getString("request_date");
String request_amount = rs.getString("request_amount");
String pool3 = rs.getString("pool");
String notes = rs.getString("request_date");
String req_status = rs.getString("req_status");
model.addRow(new Object[]{request_id, shareholder_id, username, shareholder_fname, shareholder_lname, shareholder_phone, request_date, request_amount, pool3, notes, req_status});
}
rs.close();
st.close();
conn2.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
Related
I want to insert data to my table, I have an insert statement (to the same table) that I use in a different method which works in one method, but returns an JdbcSQLSyntaxErrorException: Column xyz not found; in another.
where xyz is the value I want to pass into the column (not the column name).
This is the method which triggers the exception:
public void btnSaveStock(MouseEvent mouseEvent) {
ArrayList<Stock> stock = new ArrayList<>();
stock.addAll(tblStock.getItems());
stock.remove(removedStock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
for (int i = 0; i < stock.size(); i++) {
String stockName = stock.get(i).getDescription();
String stockCode = stock.get(i).getCode();
double fuelBalance = stock.get(i).getStoresBalance();
double counterBalance = stock.get(i).getCounterBalance();
System.out.println(stockName + stockCode + fuelBalance + counterBalance);
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + stockCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
String updateQuery = "Update STOCK set DESCRIPTION='" + stockName + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"fuelBalance\"='" + fuelBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"counterBalance\"='" + counterBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
//more method calls here
}
This is the method that successfully inserts data:
public void addNewStock(MouseEvent mouseEvent) {
Stock stock = new Stock();
String lastCode = savedStockList.get(savedStockList.size() - 1).getCode();
int newCode = 1 + Integer.parseInt(lastCode);
stock.setCode(String.valueOf(newCode));
stock.setCounterBalance(0);
stock.setDescription("New Product");
stock.setStoresBalance(0);
savedStockList.add(stock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + newCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
initialiseStock();
}
So if stockCode contains the value xyz, the exception will be Column xyz not found
I'm failing to understand why this works in one method, but returns an exception in another.
It works because newCode is a number which doesn't need quotes and doesn't work because stockCode is a string and needs to be quoted. Add single quotes around stockCode and it should work:
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES ('" + stockCode + "','New Product','1.00','1.00')";
As a side note you should really use prepared statement.
Code example with Hibernate which evaluate possible parameters:
String query = "SELECT * FROM instances";
String where = "";
if(userName!=null) {
where+="AND username = '" + userName + "'";
}
if(componentName!=null) {
where+="AND componentname = '" + componentName + "'";
}
if(componentAlias!=null) {
where+="AND componentalias = '" + componentAlias + "'";
}
if(!where.equalsIgnoreCase("")) {
where = where.substring(3);
where = " WHERE " + where;
}
query = query + where;
LOGGER.info("Query: " + query);
Statement s = (Statement) conn.createStatement();
ResultSet rs = s.executeQuery(query);
How can I do that with Speedment ORM Filters?
It is very similar in Speedment. The Stream interface returns a new Stream every time a filter is added. You can simply store that in a variable and use if-statements as in your code.
Stream stream = instances.stream();
if (userName != null) {
stream = stream.filter(Instance.USERNAME.equal(userName));
}
if (componentName != null) {
stream = stream.filter(Instance.USERNAME.equal(componentName));
}
if (componentAlias != null) {
stream = stream.filter(Instance.USERNAME.equal(componentAlias));
}
List<Instance> result = stream.collect(toList());
I need to import csv into access database using java. I tried using the following code
my code:
public static void main (String args[])
{
String dbFileSpec = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\Centre.accdb";
// String accessTableName = "Centre";
String csvDirPath = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase";
String csvFileName = "myjdbcfile.csv";
try (Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://" + dbFileSpec
// + ";newdatabaseversion=V2007"
)) {
try
{
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
System.err.println("SQL --> "+strSQL);
PreparedStatement selectPrepSt = conn.prepareStatement(strSQL);
boolean result = selectPrepSt.execute();
System.out.println("result = " + result);
}
catch(SQLException ex)
{
System.err.println("Error --->"+ex.toString());
}
conn.commit();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But it throws error as "net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: INTO required: FROM".
The two problems with trying to use
SELECT ... INTO NewTableName FROM [Text; ...].[csvFileName]
in this context are:
SELECT ... INTO NewTableName FROM OldTableName is an Access SQL construct that UCanAccess does not support (at least not at the moment), and
... FROM [Text; ...].[csvFileName] is an ODBC "trick" and UCanAccess does not use ODBC.
However, UCanAccess uses HSQLDB and HSQLDB offers support for reading CSV files like so:
final String csvFolder = "C:/__tmp/zzzTest/";
final String csvFileName = "myjdbcfile.csv";
final String csvDbName = "hsqldbTemp";
try (Connection hconn = DriverManager.getConnection(
"jdbc:hsqldb:file:" + csvFolder + "/" + csvDbName,
"SA",
"")) {
try (Statement s = hconn.createStatement()) {
s.executeUpdate("CREATE TEXT TABLE fromcsv (id int, textcol varchar(50))");
s.executeUpdate("SET TABLE fromcsv SOURCE \"" + csvFileName + "\" DESC");
try (ResultSet rs = s.executeQuery("SELECT * FROM fromcsv")) {
while (rs.next()) {
System.out.println(rs.getString("textcol"));
}
}
s.executeUpdate("SHUTDOWN");
File f = null;
f = new File(csvFolder + "/" + csvDbName + ".properties");
f.delete();
f = new File(csvFolder + "/" + csvDbName + ".script");
f.delete();
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
so you could use two connections,
one jdbc:ucanaccess connection to the Access database, and
another jdbc:hsqldb connection to the CSV file,
and then insert the rows from the CSV file into a table in the Access database.
You have mis-typed the query here,
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM
[Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
should be ,
String strSQL = "SELECT *" + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
Im trying to execute a query through a java program but it doesn't execute. here's the method
public List<Usuario> darProveedores() throws Exception{
PreparedStatement st=null;
ArrayList<Usuario> respuesta = new ArrayList<Usuario>();
String consulta ="SELECT u.direccion_electronica AS dirE, "
+ "u.login AS login, "
+ "u.palabra_clave AS clave, "
+ "u.rol AS rol, "
+ "u.tipo_persona AS tipoPer, "
+ "u.documento_identificacion AS docID, "
+ "u.nombre AS nombre, "
+ "u.nacionalidad AS naci, "
+ "u.direccion_fisica AS dirF, "
+ "u.telefono AS tel, "
+ "u.ciudad AS ciudad, "
+ "u.departamento AS depto, "
+ "u.codigo_postal AS codPostal "
+ " FROM usuarios u "
+ " WHERE u.rol='Proveedor' ";
try{
iniTemp();
establecerConexion(cadenaConexion, usuario, clave);
st = conexion.prepareStatement(consulta);
ResultSet r= st.executeQuery(consulta);
while(r.next()){
String dirE= r.getString("dirE");
String login = r.getString("login");
String clave = r.getString("clave");
String rol = r.getString("rol");
String tipoPer = r.getString("tipoPer");
String docID = r.getString("docID");
String nombre = r.getString("nombre");
String naci = r.getString("naci");
String dirF = r.getString("dirF");
String tel= r.getString("tel");
String ciudad = r.getString("ciudad");
String depto = r.getString("depto");
String codPostal = r.getString("codPostal");
Usuario u = new Usuario(login, dirE, clave, rol, tipoPer, Integer.parseInt(docID), nombre, naci, dirF, Integer.parseInt(tel), ciudad, depto, Integer.parseInt(codPostal));
respuesta.add(u);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if (st != null)
{
try {
st.close();
} catch (SQLException exception) {
throw new Exception("ERROR: ConsultaDAO: loadRow() = cerrando una conexion.");
}
}
closeConnection(conexion);
}
return respuesta;
}
I have executed the query on SQL Developer and it returns a table with values, but when
i do it through here the while(r.next()) instruction says there are no rows in the answer
You don't need to use a PreparedStatement when there are no parameters. Just use Statement in place of PreparedStatement, and st = conexion.createStatement() to create it.
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.