h2|Java Column not found (but statement works elsewhere) - java

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.

Related

Unknown column 'PROGRAMMEDescription' in 'field list'

I'm trying to write a servlet which makes a query to a database, but when it runs, I get this error:
java.sql.SQLSyntaxErrorException: Unknown column 'PROGRAMMEDescription' in 'field list'
The code:
response.setContentType("text/html; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String requestType= request.getParameter("requestType");
if (requestType == null) {
createDynPage(response, "Μη έγκυρος τύπος ερωτήματος");
}
if (requestType.equalsIgnoreCase("insert")) {
String descr = request.getParameter("descr");
String mins = request.getParameter("mins");
String sms = request.getParameter("sms");
String mb = request.getParameter("mb");
String pagio = request.getParameter("pagio");
String minstoall = request.getParameter("minstoall");
String costpermin = request.getParameter("costpermin");
String costpersms= request.getParameter("costpersms");
String costpermb = request.getParameter("costpermb");
int m = Integer.parseInt(mins);
int s = Integer.parseInt(sms);
int d = Integer.parseInt(mb);
float fc=Float.parseFloat(pagio);
int mta = Integer.parseInt(minstoall);
float cpm=Float.parseFloat(costpermin);
float cps=Float.parseFloat(costpersms);
float cpmb=Float.parseFloat(costpermb);
try {
Connection con = datasource.getConnection();
Statement stmt = con.createStatement();
StringBuilder x = new StringBuilder();
String insertStmt = "INSERT INTO CUSTOMERS (PROGRAMMEDescription, PROGRAMMESpeechTime, PROGRAMMESMSNumber, PROGRAMMEData, PROGRAMMEFixedCost, PROGRAMMESpeechTimeToAll, PROGRAMMECostPerMinute, PROGRAMMECostPerSMS, PROGRAMMECostPerMB)" +
" VALUES (";
insertStmt += "'" + descr + "',";
insertStmt += m + ",";
insertStmt += s + ",";
insertStmt += d + ",";
insertStmt += fc + ",";
insertStmt += mta + ",";
insertStmt += cpm + ",";
insertStmt += cps + ",";
insertStmt += cpmb + ")";
stmt.executeUpdate(insertStmt);
createDynPage(response, "Το πρόγραμμα δημιουργήθηκε επιτυχώς!");
stmt.close();
con.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
} else {
createDynPage(response, "The request type parameter must be insert");
}
The table:
As you can see from both the code and the table, the column PROGRAMMEDescription exists normally. I can't understant why Java think it doesn't. Any ideas?
I think it may be because the field is not in the database! Perhaps you should get the sql statement executed this time and execute it once in the database to determine whether the field exists in the database!

Connection to remote Mysql database closing

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

importing data from csv file into access database using java

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 + "]";

Inserting records into a MySQL table using Java

I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

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