I curently work on few SQL queries (MSSQL 2O14), but only "SELECT" query works with executeQuery().
I had use execute() and executeUpdate() on "INSERT INTO" and "UPDATE" queries, but whereas it looks like working, no way.
FYI, in "UPDATE_PREVIOUS_H_LOT_STATUT,
int count= p.executeUpdate(); return 1. If h_lot_number is an unknown lot number, count = 0.
So, if I use wrong data in input, my query isn't executed(Until here, I agree) but when I use the expected data, the query is executed but there is no change in my DB.
How can I find where my error is ?
UPDATE Function :
public static boolean UPDATE_PREVIOUS_H_LOT_STATUT(String h_lot_number_old) {
try {
setUpConnexion("mainDB");
String baseQuery = "UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'";
//PreparedStatement p = newTransact("UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'", "mainDB");
PreparedStatement toReturn = (PreparedStatement) mainCon.prepareStatement(baseQuery);
int count = toReturn.executeUpdate();
if (count > 0) {
Log.d("Sucess : ", "Previous h_lot updated.");
closeCons();
return true;
} else {
Log.e("Error : ", "No lot found with this number.");
closeCons();
return false;
}
} catch (SQLException e) {
error = e.getMessage();
Log.e("Error :", error);
closeCons();
return false;
}
}
LOAD PREVIOUS NUMBER FUNCTION (works perfectly)
public static String LOAD_PREVIOUS_H_LOT_NUMBER(String machineNumber) {
String s = "";
try {
setUpConnexion("mainDB");
ResultSet RS = executeQuery("SELECT h_lot_number FROM valve_assembly_h WHERE machine_number = '" + machineNumber + "' AND statut = 'Actif'", "mainDB");
while (RS.next()) {
s = RS.getString(1);
Log.d("Success : ", "Lot number : " + s);
}
closeResultSet(RS);
} catch (Exception e) {
error = e.getMessage();
Log.e("Error :", error);
s = error;
}
closeCons();
return s;
}
Set up connection function : (works perfectly)
public static boolean setUpConnexion(String DBNAME) {
StrictMode.ThreadPolicy policy;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectURL;
try {
CONNECTION MS SQL SERVER
}
return true;
} catch (Exception e) {
System.out.println("SQL ERROR: " + e.getMessage());
e.printStackTrace();
return false;
}
}
Try to commit the transaction manually through the Connection object ,hope it helps.
I have a form that has a ComboBox which it gets its items from a database. The combobox takes numerous column-items from a table inside the database.
I want to take only one of these items (from the combobox) and copy it to a JTextField.
Here's the code of the creation of the ComboBox in the Order.java file:
cbinv = new JComboBox<>();
cbinv.setModel(new InvComboModel(con));
and the code from the InvComboModel.java:
public InvComboModel(Connection con) {
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM inventory";
rs = stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println("InvComboModel: " + e.getMessage());
}
}
#Override
public String getElementAt(int index) {
String lstn = null;
try {
rs.absolute(index + 1);
lstn = rs.getString("category") + ", " + rs.getString("description") + ", "
+ rs.getInt("price") + ", " + rs.getInt("quantity");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return lstn;
}
#Override
public int getSize() {
int cnt = 0;
try {
rs.last();
cnt = rs.getRow();
} catch (SQLException ex) {
System.out.println("getSize(): " + ex.getMessage());
}
return cnt;
}
public int getIdInvAt(int index) {
int idInv = 0;
try {
rs.absolute(index + 1);
idInv = rs.getInt("idinv");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return idInv;
}
So, I want when I select something on the Inventory Item to take the third value (which in this case is 500, example image) and copy it to the JTextField of the ItemPrice.
[example][1]: https://i.stack.imgur.com/BWQVw.jpg
In the Order.java file I have the following command but it copies all the selected item in the combobox:
tip.setText((String) cbinv.getSelectedItem());
and when I use the following command it takes the whole line again. It seems that I can't use any other method from the InvComboModel.java file
tip.setText((String) cbinv.getModel().getElementAt());
Thanks in advance.
Alright so I need help in reviewing my codes because I'm kinda still new in programming (currently in my second year of Diploma in Computer Science). I got this error as in the title GC Overhead Limit Exceeded when I tried running my code below.
A brief explanation of this code, I'm trying to read data from a CSV File and then transfer it to a database. FYI, there are actually 10 tables/CSV files that I need to read, but on this I'll show this one table Tickets because the error only occurred when I tried to read that table/file. The other tables have hundreds of rows/data only while the table Tickets have 735,504 of rows/data. Furthermore, I've succeeded in reading 450,028 of data after 6 hours of running the code before the error occurred.
What can I do to fix this error? What can be modified to improve my code? I really appreciate it if you guys can help me :)
public class Demo2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database";
String username = "root";
String password = "password";
try {
//Connect to the database
Connection connection = DriverManager.getConnection(url, username, password);
//Test on one table only
String tableName = "Tickets";
System.out.println("Connecting to TABLE " +tableName +"...");
readCSVFile(tableName, connection);
System.out.println();
System.out.println("THE END");
connection.close();//close connection to the database
}
catch (SQLException e) {
System.out.println("ERROR at main(): SQLException!!");
e.printStackTrace();
}
}
static int countNewRow = 0;
static int countUpdatedRow = 0;
//Method to read the CSV File
static void readCSVFile(String tableName, Connection conn) {
//Read CSV File
try {
String path = tableName +".csv";
BufferedReader br = new BufferedReader(new FileReader(path));
br.readLine();//skip the first line
String inData;
//Read The Remaining Line
while((inData=br.readLine()) != null)
{
String[] rowData = inData.split(",");
ArrayList <String> rowDataList = new ArrayList<String>();
for (int i=0; i<rowData.length; i++)
rowDataList.add(rowData[i]);
//To combine String that starts and ends with "
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).charAt(0) == '"') {
String string1 = rowDataList.get(i).substring(1, rowDataList.get(i).length());
String string2 = rowDataList.get(i+1).substring(0, rowDataList.get(i+1).length()-1);
String combined = string1 +"," +string2;
rowDataList.set(i, combined);
rowDataList.remove(i+1);
break;
}
}
//Remove the RM
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).startsWith("RM")) {
String string = rowDataList.get(i).substring(2);
rowDataList.set(i, string);
}
}
//This is just to keep track of the data that has been read
System.out.println("[" +rowDataList.get(0) +"]");
//Transfer the data to the database
insertToDatabase(conn, tableName, rowDataList);
}
System.out.println("New Row Added : " +countNewRow);
System.out.println("Updated Row : " +countUpdatedRow);
System.out.println("== Process Completed ==");
br.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR at readCSVFile(): FileNotFoundException!!");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("ERROR at readCSVFile(): IOException!!");
e.printStackTrace();
}
catch (SQLException e) {
System.out.println("ERROR at readCSVFile(): SQLException!!");
e.printStackTrace();
}
catch (ParseException e) {
System.out.println("ERROR at readCSVFile(): ParseException!!");
e.printStackTrace();
}
}
static void insertToDatabase(Connection connection, String tableName, ArrayList <String> rowDataList) throws SQLException, ParseException {
String tableIdName = tableName;
if (tableIdName.charAt(tableIdName.length()-1) == 's')
tableIdName = tableIdName.substring(0, tableIdName.length()-1);
//To read row
String rowID = rowDataList.get(0);
String selectSQL = "SELECT * FROM " +tableName +" "
+"WHERE " +tableIdName +"_ID = " +rowID;
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(selectSQL);
boolean value = result.next();
//INSERT # UPDATE row
if (value == true) { //Update Row if the data is already existed
updateStatementt(tableName, connection, rowDataList);
countUpdatedRow++;
}
else { //Insert New Row
insertStatementt(tableName, connection, rowDataList);
countNewRow++;
}
}
//Method to insert data to the database
static void insertStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException, ParseException {
//Generate Question Mark
String generateQuestionMark = null;
if(rowDataList.size() == 1)
generateQuestionMark = "?";
else
generateQuestionMark = "?, ";
for(int i=1; i<rowDataList.size(); i++) {
if(i!=rowDataList.size()-1)
generateQuestionMark += "?, ";
else
generateQuestionMark += "?";
}
//Insert sql
String sql = "INSERT INTO " +tableType +" VALUES (" +generateQuestionMark +")";
PreparedStatement insertStatement = conn.prepareStatement(sql);
//Insert data
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
int ticketID = Integer.parseInt(rowDataList.get(0));
int movieId = Integer.parseInt(rowDataList.get(1));
int theaterId = Integer.parseInt(rowDataList.get(2));
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
Date showDate = Date.valueOf(dateString);
int showTimeId = Integer.parseInt(rowDataList.get(4));
int cptId = Integer.parseInt(rowDataList.get(5));
int pcId = Integer.parseInt(rowDataList.get(6));
float amountPaid = Float.parseFloat(rowDataList.get(7));
int year = Integer.parseInt(rowDataList.get(8));
String month = rowDataList.get(9);
insertStatement.setInt(1, ticketID);
insertStatement.setInt(2, movieId);
insertStatement.setInt(3, theaterId);
insertStatement.setDate(4, showDate);
insertStatement.setInt(5, showTimeId);
insertStatement.setInt(6, cptId);
insertStatement.setInt(7, pcId);
insertStatement.setFloat(8, amountPaid);
insertStatement.setInt(9, year);
insertStatement.setString(10, month);
}
insertStatement.executeUpdate();
insertStatement.close();
}
//Method to update the data from the database
static void updateStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException {
Statement statement = conn.createStatement();
String sql = "UPDATE " +tableType;
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
sql += " SET movie_id = " +rowDataList.get(1) +","
+ " theater_id = " +rowDataList.get(2) +","
+ " showdate = \"" +dateString +"\","
+ " showtime_id = " +rowDataList.get(4) +","
+ " costperticket_id = " +rowDataList.get(5) +","
+ " personcategory_id = " +rowDataList.get(6) +","
+ " amount_paid = " +rowDataList.get(7) +","
+ " year = " +rowDataList.get(8) +","
+ " month = \"" +rowDataList.get(9) +"\""
+ " WHERE ticket_id = " +rowDataList.get(0);
}
statement.executeUpdate(sql);
}
}
For short, read a single line and do whatever you want to do with it. You don't have enough memory for all 700k lines.
You should add statement.close() for the update Statement.
If you really want to read all this data into the Java heap, increase the heap size using, for example, the -Xmx command-line switch. Because of the way textual data is encoded in the JVM, you'll probably need much more heap that the total data size would suggest.
In addition, there might be some places in your code where you can take the strain off the JVM's memory management system. For example, concatenating strings using "+" can generate a lot of temporary data, which will increase the load on the garbage collector. Assembling strings using a StringBuilder might be a simple, less resource-hungry, alternative.
I want to insert the data in array so I can access specific values and display them. I am a newbie to java and I would like the answer to be simple.
try {
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM " + tableName;
ResultSet results = stmt.executeQuery(sql);
ResultSetMetaData rsmt = results.getMetaData();
int numberOfColumns = rsmt.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
System.out.print(rsmt.getColumnLabel(i) + "\t\t\t");
}
System.out.println("\n-------------------------------------------------------------------------------");
while (results.next()) {
int s_no = results.getInt(1);
String s_name = results.getString(2);
String s_surname = results.getString(3);
System.out.println(s_no + "\t\t\t" + s_name + "\t\t\t" + s_surname);
}
results.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Records were not returned", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e.getMessage());
}
storing resultset data in array is not possible.
better to create pojo class Student
public class Student {
private int s_no;
private String s_name;
private String s_surname;
public int getS_no() {
return s_no;
}
public void setS_no(int s_no) {
this.s_no = s_no;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
public String getS_surname() {
return s_surname;
}
public void setS_surname(String s_surname) {
this.s_surname = s_surname;
}
}
Storing logic :-
ResultSet results = stmt.executeQuery(sql);
List<Student> studs = new ArrayList<Student>();
while (results.next()){
Student stud = new Student();
stud.setS_no(results.getInt(1));
stud.setS_name(results.getString(2));
stud.setS_surname(results.getString(3));
studs.add(stud);
}
all students have been added in list. Please iterate this list to fetch student data.
hope this will work for you
I've been working with a project that requires me to use mutiple jcombobox. I did try to chain three jcombobox but failed to show all necessary drop-down lists.
In one of my combobox I have lists of Banks (Bank1, Bank2), the other one is the list of all branches in a specific Bank that has been selected (Bank1(branch1-1, branch1-2), Bank2(branch2-1, branch2-2)) and the last one are the account # for all specific branches that has been selected. Each branches has a multiple accounts.
I have no problem working with 2 comboboxes, all branches are shown for a specific Bank that has been selected, but, when I added the third combobox which is the account #, only one branch is being queried from my db. ex. if I select Bank1 only "branch1" will be on the list, and if Bank2 only branch2-1 will be on the list also, but account # for that specific branches are on the drop-down lists.
private void populateSavingsAccountComboBox() {
accountNo.removeAllItems();
bankBranch.removeAllItems();
selectBank();
bankName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String bank = bankName.getSelectedItem() == null ?
"" : bankName.getSelectedItem().toString();
selectBranch(bank);
}
});
bankBranch.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
JComboBox target = (JComboBox) e.getSource();
String branch = target.getSelectedItem() == null ?
"" : target.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED) {
selectAccountNo(bankName.getSelectedItem().toString(), branch);
}
}
});
}
private void selectBank() {
List bankList = new ArrayList();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(" SELECT bankName FROM bank_tbl ");
bankName.removeAllItems();
while (rs.next()) {
String bank = rs.getString("bankName");
bankList.add(bank);
Object bankElement = bankList.get(bankList.size() - 1);
bankName.addItem(bankElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String selectBranch(String bank) {
try {
List branchList = new ArrayList();
rs = stmt.executeQuery(" SELECT branch FROM bank_branch_tbl WHERE "
+ " bankName = '" + bank + "' ");
bankBranch.removeAllItems();
while (rs.next()) {
branchList.add(rs.getString("branch"));
Object branchElement = branchList.get(branchList.size() - 1);
bankBranch.addItem(branchElement);
}
} catch (SQLException ex) {
Logger.getLogger(addContact.class.getName()).log(Level.SEVERE, null, ex);
}
return bank;
}
private String selectAccountNo(String bank, String branch) {
List accountNoList = new ArrayList();
try {
rs = stmt.executeQuery(" SELECT accountNo FROM account_no_tbl WHERE "
+ " bankName = '" + bank + "' AND "
+ " branch = '" + branch + "' ");
accountNo.removeAllItems();
while (rs.next()) {
accountNoList.add(rs.getString("accountNo"));
Object accountNoElement = accountNoList.get(accountNoList.size() - 1);
accountNo.addItem(accountNoElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
return branch;
}
problem solved. I was using one-single variable for all ResultSet. tsk! thank you for replying to my post.