error insert data in java netbeans and mysql - java

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}

For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}

I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

Related

How to get data from an ArrayList <List> in another class?

I'm using RecyclerView I have an Activity that queries my database and I insert this data into that ArrayList , and I want to list that data in another Activity.
This is where I query and add the data to the ArrayList
String queryProduto = "SELECT" +
" Produto_Servico.ID, Produto_Servico.Descricao," +
" Produto_Estoque.EstoqueAtual, ValorVenda" +
" FROM" +
" Produto_Valor" +
" INNER JOIN" +
" Produto_Servico" +
" ON" +
" Produto_Servico.ID = Produto_Valor.ID_Produto" +
" INNER JOIN" +
" Produto_Estoque" +
" ON" +
" Produto_Estoque.ID_Produto = Produto_Servico.ID" +
" WHERE" +
" Produto_Estoque.EstoqueAtual > 0" +
" ORDER BY" +
" Produto_Servico.Descricao";
Statement stmtP = connect.createStatement();
ResultSet rsP = stmtP.executeQuery(queryProduto);
String queryPessoa = "SELECT ID_Pessoa FROM Novo_Pedido";
Statement stmtPS = connect.createStatement();
ResultSet rsPS = stmtPS.executeQuery(queryPessoa);
while (rsPS.next()){
cod = rsPS.getString("ID_Pessoa");
}
if (rsP != null) {
while (rsP.next()) {
id = String.valueOf(rsP.getString("ID"));
desc = rsP.getString("Descricao");
estoque = String.valueOf(rsP.getString("EstoqueAtual"));
valorDec = rsP.getBigDecimal(4);
qtdStr = String.valueOf(qtd);
valorStr = decimalFormat.format(valorDec);
String descFinal = desc;
String qtdFinal = qtdStr;
final BigDecimal[] valorFinal = {valorDec};
try {
listProdutosPedidosFinalizar.add(new ListProdutosPedidosFinalizar(descFinal, qtdFinal, valorFinal[0], BigDecimal.ZERO));
classeLists.setListProdutosPedidosFinalizar(listProdutosPedidosFinalizar);
produtosPedidosAdapter = new ProdutosPedidosAdapter(listProdutosPedidos, this, new ProdutosPedidosAdapter.OnClickListener() {
/*METHODS*/
produtosPedidosAdapter.notifyDataSetChanged();
listProdutosPedidos.add(new ListProdutosPedidos(id, desc, estoque, valorStr, qtdStr));
} catch (Exception ex) {
ex.printStackTrace();
}
rvProdutosPedidos.setAdapter(produtosPedidosAdapter);
produtosPedidosAdapter.notifyDataSetChanged();
isSuccess = true;
}
And now I want to list the listProdutosPedidos data in another Activity.
Define listProdutosPedidos list as static member of your class and then use className.listProdutosPedidos code to access records in it.

How to get the value if resultset matched with the entire row value?

Here I attached my code. When if stateVector contains the statename I need to check the that entire row only, not all the icd and dicd vector value. How I need to do that?
In my code its checking all vectors once the statename matched with any other or icdid it's showing it's available.
public class LCDEdits
{
#SuppressWarnings("unchecked")
public String validateICD_CPT(String cptCode, String stateName, String icdCode) throws Exception
{
/**** Variable Initialization ***/
String lcdRes = null;
StringBuffer lcdSql = null;
// String error = null;
java.sql.Connection con = null;
java.sql.PreparedStatement poStmt1 = null;
DBConfig db1 = null;
ResultSet rs = null;
JSONObject JObj = new JSONObject();
try
{
lcdSql = new StringBuffer(" SELECT cpt.hcpc_code, cpt.lcd_id, statepri.state_abbr, icd.icd10_id, ");
lcdSql.append(" dicd.icd10_id_dont FROM lcd_cpt cpt ");
lcdSql.append(" LEFT JOIN lcd_statepri statepri ON(cpt.lcd_id = statepri.lcd_id) ");
//lcdSql.append(" LEFT JOIN lcd_statesec statesec ON( cpt.lcd_id = statesec.lcd_id) ");
lcdSql.append(" LEFT JOIN lcd_icd_support icd ON( cpt.lcd_id = icd.lcd_id) ");
lcdSql.append(" LEFT JOIN lcd_icd_dont_support dicd ON( cpt.lcd_id = dicd.lcd_id) ");
lcdSql.append(" WHERE hcpc_code = ? ");
db1 = new DBConfig();
con = db1.openConn();
poStmt1 = con.prepareStatement(lcdSql.toString());
poStmt1.setString(1, cptCode);
rs = poStmt1.executeQuery();
Vector<String> stateVector = new Vector<String>();
Vector<String> icdVector = new Vector<String>();
Vector<String> dicdVector = new Vector<String>();
while(rs.next())
{
stateVector.add(rs.getString("state_abbr") );
// icdVector.add(rs.getString("icd10_id") );
// dicdVector.add(rs.getString("icd10_id_dont") );
//stateVector.add(rs.getString("sec_state_abbr") );
}
if(stateVector.contains(stateName))
{
if(icdVector.contains(icdCode))
{
// String lcd_icd = lcd_Id;
lcdRes = "CPT-Code is Available in LCD Database.";
// lcdRes1 = "As for the LCD-Code " +lcd_icd+ ", the CPT-Code " + cptCode + " is supported the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
else if(dicdVector.contains(icdCode))
{
lcdRes = "Medicare is not interest to pay Amount for this CPT-Code.";
// lcdRes1 = "As for the LCD-Code " +lcd_Id+ ", the CPT-Code " +cptCode+ " is not supported the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
else
{
lcdRes = "CPT-Code is not available in the LCD-Database.";
// lcdRes1 = "As for the LCD-Code " +lcd_Id+ ", the CPT-Code " +cptCode+ " is not applicable for the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
}
else
{
// String lcd_state = lcd_Id;
lcdRes = "State not matched with LCD-Code.";
// lcdRes1 = "As for the LCD-Code " +lcd_state+ ", the CPT-Code " +cptCode+ " is not applicable in the state of " +stateName+ ".";
}
JObj.put("status", "success");
JObj.put("res_msg", lcdRes);
// JObj.put("dis_msg", lcdRes1);
}
catch(Exception ex) {
ex.printStackTrace();
JObj.put("status", "failed");
}
finally {
rs.close();
poStmt1.close();
db1.closeConnection(con);
}
return JObj.toString();
}
}
First, separate the reading from the database and the processing of the data.
Vector stateVector = null;
try {
Reading data from database
} catch (the problems) {
And handle them
} finally {
close the connection
}
then check if you have some data:
if (stateVector != null {
// get the data you want, probably with a loop construct
}

How to check if id is exists in Android?

I want to check if id is exists in SQLIte DB then update that id , if id is not present in SQLite then insert that id. How can i do this. Can someone help how to work with.Thanks to Appreciate.
Here is my Activity code
public void saveResult()
{
AnswerOptions = (RadioButton) findViewById(Options_RadioGroup.getCheckedRadioButtonId());
String str_AnswerOptions = AnswerOptions.getText().toString().trim();
System.out.println("rbVal = " + str_AnswerOptions);
if (str_AnswerOptions.equals(((Datastructure) Vectore_mquestionDatabaseStructure .get(StaticClass.QuestionNumber)).Answer))
{
if (!StaticClass.isTest)
{
try
{
DatabaseHelper databaseHelper = new DatabaseHelper(this.getApplicationContext());
sqdb = databaseHelper.getWritableDatabase();
String strCountQuery = "SELECT question_id, question_type , question_no FROM question_answers where question_id = " + convertVector ;
Cursor cur = sqdb.rawQuery(strCountQuery , null);
if (cur.moveToFirst())
{
int iCount = cur.getCount();
System.out.println("iCount = " + iCount);
if(cur.getCount() <= 0 )
{
String strstrqueType = txtViewQuestiontype.getText().toString().trim();
String str_que = txtViewQuestion.getText().toString().trim();
String str_marks = "1";
databaseHelper.insertQueDetails(strQueLimit, strstrqueType, str_que, str_AnswerOptions, str_marks , strOption_Id);
System.out.println("strQueLimit = " + strQueLimit + ", strstrqueType = " + strstrqueType +" , str_que = " + str_que + " , str_AnswerOptions = " + str_AnswerOptions + ", str_marks = " + str_marks + ", strOption_Id = " + strOption_Id);
Toast.makeText(this, " Right Answer ", Toast.LENGTH_LONG).show();
}
else
{
cur.moveToFirst();
qid = cur.getInt(cur.getColumnIndex("question_id"));
String strQue_Type = cur.getString(cur.getColumnIndex("question_type"));
String strQue_Nomber = cur.getString(cur.getColumnIndex("question_no"));
System.out.println("qid in checkUpdateTable() = " + qid);
System.out.println("strQue_Type in checkUpdateTable() = " + strQue_Type);
System.out.println("strQue_Nomber in checkUpdateTable()= " + strQue_Nomber);
QueId = qid;
databaseHelper.updateAnswerRow(qid, str_AnswerOptions);
}
}
}
catch (SQLiteException se )
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{ if (sqdb != null) { sqdb.close();} }
}
}
}
You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:
CREATE TABLE data (id INTEGER PRIMARY KEY, question_id INTEGER, question_type TEXT, question_no TEXT);
CREATE UNIQUE INDEX data_idx ON data(question_id);
Then you can issue:
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

How to Make a cursor Type scroll insensitive in jdbc usin sqlite

Hey im attempting to to make an invoice program that uses Java and Sqlite as a database. I know that sqlite is a forward only language, but is there a way to scroll backwards or make it type scroll insensitive here is the class that im trying to use. I am attempting to put all of my information extracted from my database into an array.
public String[] getRow(int rowID)
{
String id =("");
String name = ("");
String day = ("");
String location = ("");
String price = ("");
String timestart= ("");
String Timeend = ("");
String Showtype = ("");
String[] row= new String[8];
try
{
Class.forName("org.sqlite.JDBC");
Connection x=DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = x.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery ("SELECT ID, NAME, day, Location, price, timestart, Timeend, Showtype FROM Showinformation ORDER BY ID LIMIT 5 OFFSET:index;");
rs.step(rowID);
while(rs.next())
{
for(int i=0; i<8; i++)
{
id = rs.getString("ID");
row[0]=id;
name = rs.getString("NAME");
row[1]=name;
day = rs.getString("day");
row[2]=day;
location = rs.getString("Location");
row[3]=location;
price = rs.getString("price");
row[4]=price;
timestart= rs.getString("timestart");
row[5]=timestart;
Timeend= rs.getString("Timeend");
row[6]=Timeend;
Showtype= rs.getString("Showtype");
row[7]=Showtype;
}
//String potato =(i+1+id+""+name+""+day+""+location+""+price+""+timestart+""+Timeend+""+Showtype);
//System.out.println("ID = " + id +"\nNAME = " + name+"\nDAY = " + day+"\nADDRESS = " + location+"\nPRICE = " + price+"\nTIME START = " + timestart+"\nTIME END = " + Timeend+"\nSHOWTYPE = " + Showtype );
}
}
catch(Exception er)
{
System.err.println(er.getClass().getName()+":"+er.getMessage() );
}
return row;
}
any help would be appreciated.

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