Update MySQL table using data from a text file through Java - java

I have a text file with four lines, each line contains comma separated values like below file
My file is:
Raj,raj34#myown.com,123455
kumar,kumar#myown.com,23453
shilpa,shilpa#myown.com,765468
suraj,suraj#myown.com,876567
and I have a MySQL table which contains four fields
firstname lastname email phno
---------- ---------- --------- --------
Raj babu raj34#hisown.com 2343245
kumar selva kumar#myown.com 23453
shilpa murali shilpa#myown.com 765468
suraj abd suraj#myown.com 876567
Now I want to update my table using the data in the above text file through Java.
I have tried using bufferedReader to read from the file and used split method using comma as delimiter and stored it in array. But it is not working. Any help appreciated.
This is what I have tried so far
void readingFile()
{
try
{
File f1 = new File("TestFile.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String strln = null;
strln = br.readLine();
while((strln=br.readLine())!=null)
{
// System.out.println(strln);
arr = strln.split(",");
strfirstname = arr[0];
strlastname = arr[1];
stremail = arr[2];
strphno = arr[3];
System.out.println(strfirstname + " " + strlastname + " " + stremail +" "+ strphno);
}
// for(String i : arr)
// {
// }
br.close();
fr.close();
}
catch(IOException e)
{
System.out.println("Cannot read from File." + e);
}
try
{
st = conn.createStatement();
String query = "update sampledb set email = stremail,phno =strphno where firstname = strfirstname ";
st.executeUpdate(query);
st.close();
System.out.println("sampledb Table successfully updated.");
}
catch(Exception e3)
{
System.out.println("Unable to Update sampledb table. " + e3);
}
}
and the output i got is:
Ganesh Pandiyan ganesh1#myown.com 9591982389
Dass Jeyan jeyandas#myown.com 9689523645
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Gowtham Selvan gowthams#myown.com 9894189423
at TemporaryPackages.FileReadAndUpdateTable.readingFile(FileReadAndUpdateTable.java:35)
at TemporaryPackages.FileReadAndUpdateTable.main(FileReadAndUpdateTable.java:72)
Java Result: 1
#varadaraj:
This is the code of yours....
String stremail,strphno,strfirstname,strlastname;
// String[] arr;
Connection conn;
Statement st;
void readingFile()
{
try {
BufferedReader bReader= new BufferedReader(new FileReader("TestFile.txt"));
String fileValues;
while ((fileValues = bReader.readLine()) != null)
{
String[] values=fileValues .split(",");
strfirstname = values[0];
// strlastname = values[1];
stremail = values[1];
strphno = values[2];
System.out.println(strfirstname + " " + strlastname + " " + stremail +" "+ strphno);
}
bReader.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
// for(String i : arr)
// {
// }
try
{
st = conn.createStatement();
String query = "update sampledb set email = stremail,phno =strphno where firstname = strfirstname ";
st.executeUpdate(query);
st.close();
System.out.println("sampledb Table successfully updated.");
}
catch(Exception e3)
{
System.out.println("Unable to Update sampledb table. " + e3);
}
}

What you are having looks like a CSV file, you may consider libraries like Super CSV to help you in reading and parsing the file.

you are getting ArrayIndexOutOfBoundException upon trying to access at index 1 , i.e at lastname field value, so check whether you have no data at index 1 for any of the list elements in your text file

try this
public class FileReaderTesting {
static String stremail;
static String strphno;
static String strfirstname;
static String strlastname;
static Connection conn;
static Statement st;
public static void main(String[] args) {
try {
BufferedReader bReader= new BufferedReader(new FileReader("C:\\fileName.txt"));
String fileValues;
while ((fileValues = bReader.readLine()) != null)
{
String[] values=fileValues .split(",");
strfirstname = values[0];
// strlastname = values[1];
stremail = values[1];
strphno = values[2];
System.out.println(strfirstname + " " + stremail +" "+ strphno);
st = conn.createStatement();
String query = "update sampledb set email = '"+stremail+"',pno = '"+strphno+"' where firstname = '"+strfirstname+"' ";
System.out.println(query);
st.executeUpdate(query);
st.close();
System.out.println("sampledb Table successfully updated.");
}
bReader.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
catch(Exception e3)
{
System.out.println("Unable to Update sampledb table. " + e3);
}
}
}

Related

Doesn't insert csv file records in java (jdbc)

I have an error when my CSVLoader file does not insert the data in my database, I get this in my console
FieldName (UploadDownloadFileServlet) = fileName
FileName (UploadDownloadFileServlet) = prueba2.csv
ContentType (UploadDownloadFileServlet) = application/vnd.ms-excel
Size in bytes (UploadDownloadFileServlet) = 47
Absolute Path at server (UploadDownloadFileServlet) = C:\Users\SISTEMAS\workspaceEclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SAC-sin-impresion\uploadedCsvFiles\prueba2.csv
Query: INSERT INTO MATRICULA(C:UsersSISTEMASworkspaceEclipse.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsSAC-sin-impresionuploadedCsvFilesprueba2.csv) VALUES(?)
[CSVLoader]: 0 records loaded into MATRICULA DB table
THIS IS MY CODE:
public void loadCSV(InputStream csvFile, String tableName,
boolean truncateBeforeLoad) throws Exception {
CSVReader csvReader = null;
if(null == this.connection) {
throw new Exception("Not a valid connection.");
}
try {
/* Modified by rammar.
*
* I was having issues with the CSVReader using the "\" to escape characters.
* A MySQL CSV file contains quote-enclosed fields and non-quote-enclosed NULL
* values written as "\N". The CSVReader was removing the "\". To detect "\N"
* I must remove the escape character, and the only character you can replace
* it with that you are pretty much guaranteed will not be used to escape
* text is '\0'.
* I read this on:
* http://stackoverflow.com/questions/6008395/opencsv-in-java-ignores-backslash-in-a-field-value
* based on:
* http://sourceforge.net/p/opencsv/support-requests/5/
*/
// PREVIOUS VERSION: csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
csvReader = new CSVReader(new InputStreamReader(csvFile), this.seprator, '"', '\0');
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error occured while executing file. "
+ e.getMessage());
}
String[] headerRow = csvReader.readNext();
if (null == headerRow) {
throw new FileNotFoundException(
"No columns defined in given CSV file." +
"Please check the CSV file format.");
}
String questionmarks = StringUtils.repeat("?,", headerRow.length);
questionmarks = (String) questionmarks.subSequence(0, questionmarks
.length() - 1);
/* NOTE from Ron: Header column names must match SQL table fields */
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
query = query.replaceFirst(VALUES_REGEX, questionmarks);
System.out.println("Query: " + query); // Modified by rammar to suppress output
String[] nextLine;
Connection con = null;
PreparedStatement ps = null;
try {
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if(truncateBeforeLoad) {
//delete data from table before loading csv
con.createStatement().execute("DELETE FROM " + tableName);
}
final int batchSize = 1000;
int count = 0;
Date date = null;
while ((nextLine = csvReader.readNext()) != null) {
if (null != nextLine) {
int index = 1;
for (String string : nextLine) {
date = DateUtil.convertToDate(string);
if (null != date) {
ps.setDate(index++, new java.sql.Date(date
.getTime()));
} else {
/* Section modified by rammar to allow NULL values
* to be input into the DB. */
if (string.length() > 0 && !string.equals("\\N")) {
ps.setString(index++, string);
} else {
ps.setNull(index++, Types.VARCHAR);
//ps.setString(index++, null); // can use this syntax also - not sure which is better
}
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
System.out.println("[" + this.getClass().getSimpleName() + "]: " +
count + " records loaded into " + tableName + " DB table");
con.commit();
} catch (Exception e) {
con.rollback();
e.printStackTrace();
throw new Exception(
"Error occured while loading data from file to database."
+ e.getMessage());
} finally {
/*if (null != ps)
ps.close();
*/
/*if (null != con)
con.close();*/
csvReader.close();
}
}

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
}

Java CSVReader ignore commas in double quotes

I have a CSV file that I am having trouble parsing. I am using the opencsv library. Here is what my data looks like and what I am trying to achieve.
RPT_PE,CLASS,RPT_MKT,PROV_CTRCT,CENTER_NM,GK_TY,MBR_NM,MBR_PID
"20150801","NULL","33612","00083249P PCP602","JOE SMITH ARNP","NULL","FRANK, LUCAS E","50004655200"
The issue I am having is the member name ("FRANK, LUCAS E") is being split into two columns and the member name should be one. Again I'm using opencsv and a comma as the separator. Is there any way I can ignore the commas inside the double-quotes?
public void loadCSV(String csvFile, String tableName,
boolean truncateBeforeLoad) throws Exception {
CSVReader csvReader = null;
if (null == this.connection) {
throw new Exception("Not a valid connection.");
}
try {
csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error occured while executing file. "
+ e.getMessage());
}
String[] headerRow = csvReader.readNext();
if (null == headerRow) {
throw new FileNotFoundException(
"No columns defined in given CSV file."
+ "Please check the CSV file format.");
}
String questionmarks = StringUtils.repeat("?,", headerRow.length);
questionmarks = (String) questionmarks.subSequence(0, questionmarks
.length() - 1);
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
System.out.println("Base Query: " + query);
String headerRowMod = Arrays.toString(headerRow).replaceAll(", ]", "]");
String[] strArray = headerRowMod.split(",");
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(strArray, ","));
System.out.println("Add Headers: " + query);
query = query.replaceFirst(VALUES_REGEX, questionmarks);
System.out.println("Add questionmarks: " + query);
String[] nextLine;
Connection con = null;
PreparedStatement ps = null;
try {
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if (truncateBeforeLoad) {
//delete data from table before loading csv
con.createStatement().execute("DELETE FROM " + tableName);
}
final int batchSize = 1000;
int count = 0;
Date date = null;
while ((nextLine = csvReader.readNext()) != null) {
System.out.println("Next Line: " + Arrays.toString(nextLine));
if (null != nextLine) {
int index = 1;
for (String string : nextLine) {
date = DateUtil.convertToDate(string);
if (null != date) {
ps.setDate(index++, new java.sql.Date(date
.getTime()));
} else {
ps.setString(index++, string);
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
con.commit();
} catch (SQLException | IOException e) {
con.rollback();
e.printStackTrace();
throw new Exception(
"Error occured while loading data from file to database."
+ e.getMessage());
} finally {
if (null != ps) {
ps.close();
}
if (null != con) {
con.close();
}
csvReader.close();
}
}
public char getSeprator() {
return seprator;
}
public void setSeprator(char seprator) {
this.seprator = seprator;
}
public char getQuoteChar() {
return quoteChar;
}
public void setQuoteChar(char quoteChar) {
this.quoteChar = quoteChar;
}
}
Did you try the the following?
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), ',');
I wrote a following program and it works for me, I got the following result:
[20150801] [NULL] [33612] [00083249P PCP602] [JOE SMITH ARNP] [NULL]
[FRANK, LUCAS E] [50004655200]
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CVSTest {
/**
* #param args
*/
public static void main(String[] args) {
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(
"C:/Work/Dev/Projects/Pure_Test/Test/src/cvs"), ',');
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println("[" + nextLine[0] + "] [" + nextLine[1]
+ "] [" + nextLine[2] + "] [" + nextLine[3] + "] ["
+ nextLine[4] + "] [" + nextLine[5] + "] ["
+ nextLine[6] + "] [" + nextLine[7] + "]");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
According to the documentation, you can supply custom separator and quote characters in the constructor, which should deal with it:
CSVReader(Reader reader, char separator, char quotechar)
Construct your reader with , as separator and " as quotechar.
It is simple to load your CSV as an SQL table into HSQLDB, then select rows from the table to insert into another database. HSQLDB handles commas inside quotes. You need to define your text source as "quoted". See this:
http://hsqldb.org/doc/2.0/guide/texttables-chapt.html
Your case should be handled out of the box with no special configuration required.
If you can't make it work, then just switch to uniVocity-parsers to do this for you - it's twice as fast in comparison to OpenCSV, requires much less code and is packed with features.
CsvParserSettings settings = new CsvParserSettings(); // you have many configuration options here - check the tutorial.
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(new File("C:/Work/Dev/Projects/Pure_Test/Test/src/cvs")));
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException UNKNOWN COLUMN

I am currently trying to scan and parse the file that is not in sql format. I am trying to input all the data into the SQL table but for some reason every time i run the program, i get the error saying unknown column 'what' in 'field list.' So the neither of the data goes through. 'what' is one of the names that is on the text. The table currently has 11 columns. I know I am parsing or scanning it wrong but I cannot figure out where. Here is my code:
public class parseTable {
public parseTable (String name) throws FileNotFoundException
{
File file = new File(name);
parse(file);
}
private void parse(File file) throws FileNotFoundException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/";
String connectionUser = "";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
String query = "";
for(int i = 0; i < rowInfo.length; i++)
{
if(query.equals(""))
{
query = rowInfo[i];
}
else if(i == 9){
query = query + "," + rowInfo[i];
}
else if(rowInfo[i].equals(null)){
query = query + ", " + "NULL";
}
else
query = query + ", " + "'" + rowInfo[i] + "'";
}
stmt.executeUpdate("INSERT INTO dup VALUES(" + query + ")");
count = 0;
rowInfo = new String[11];
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
And this is the data I'm trying to input:
1 hello cheese 1111 what#yahoo.com user adm street zip what USA
2 Alex cheese 1111 what#yahoo.com user adm street zip what USA
So this is my new code now, using PrepareStatement. However I still get an error and I looked online for the solution on where I'm making a mistake, but I cant seem to figure out where.
String query = "INSERT INTO mil_table (UserName, NameFirst, NameLast, supportID, EmailAddress, Password,
IDQ, AddressCity, AddressState, AddressZip, AddressCountry) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
for(int i = 0; i <rowInfo.length; i++)
{
pstmt.setString(i + 1, rowInfo[i]);
}
//stmt.executeUpdate("INSERT INTO mil_table VALUES(" + query + ")");
//System.out.println("#" + query + "#");
pstmt.executeUpdate();
count = 0;
rowInfo = new String[11];
}
}
As you are using MySQL, you will need to enclose the text inputs with quotes. Try enclosing the String values that you are inserting in quotes and then execute your code.

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