I want to save the result of a whole Mysql table in an array
String sDriver = "com.mysql.jdbc.Driver";
String sURL = "jdbc:mysql://www.odorxd.xyz:3306/u218933149_odor_base";
try {
Class.forName(sDriver).newInstance();
Connection con = DriverManager.getConnection(sURL, "u218933149_estenoesodor", "Tsunayoshi27?");
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = con.prepareStatement("SELECT * FROM justname");
rs = stmt.executeQuery();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
System.out.print(rs.getString(x) + "\t");
}
System.out.println("");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
it returns this to me from the database
run:
brandon
Brandon
Julio
Daniel
BUILD SUCCESSFUL (total time: 1 second)
I want to save what is in the database in an array to be able to implement it with a sort and search method
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan", "Brandon", "Brandon Jesus", "Brandon Flores", "Brandon Flores Flores"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
that's why I need to save it in an array
I would appreciate any criticism or help as you do not have an idea, thank you
You can use a List.
List<String> list = new ArrayList<>();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
String str = rs.getString(x)
list.add(str);
System.out.print(str + "\t");
}
System.out.println();
}
String[] arr = list.toArray(new String[0]);
String temp;
// ... sort
Related
Here is the snippet of code where I want to find the multiple occurrences of animal name.
I have written the code comparing the list indexes, but unable understand how to compare the names and count the number of occurrences of each name.
List<Animals> animalList= new ArrayList<Animals>();
try {
CallableStatement stmt = conn.prepareCall(callProcedure, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
boolean results = stmt.execute();
if (results) {
ResultSet rs = stmt.getResultSet();
int count = 0;
while (rs.next()) {
Animals animal = new Animals();
animal.setAnimalName(rs.getString("animal_name"));
animal.setAge(rs.getString("age"));
animal.setHealth(rs.getString("health"));
animalList.add(animal);
count++;
}
}
int nbOccurences = 1;
for (int i = 0, length = animalList.size(); i < length; i++) {
if (i < length - 1) {
if (animalList.get(i) == animalList.get(i+1)) {
nbOccurences++;
}
} else {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //end of array
}
if (i < length - 1 && animalList.get(i) != animalList.get(i+1)) {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //moving to new element in array
nbOccurences = i;
}
}
} catch (SQLException sqlE) {
sqlE.printStackTrace();
}
return animalList;
The easiest solution, IMHO would be to stream the animal list, group by the name and count:
Map<String, Long> nameCount =
animalList.stream()
.collect(Collectors.groupingBy(Animal::getName,
Collectors.counting()));
Quick questions...
I'm trying to make a Dynamic JTree but I can't get to put every database I have into one single node for each one. This is my code so far:
jTree2 = new javax.swing.JTree();
try {
String DSN = "jdbc:mysql://localhost";
String user = "root";
String password = "";
conexion = DriverManager.getConnection(DSN, user, password);
}
catch(Exception e) {
System.out.println("ERROR");
}
try {
sentencia = conexion.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception e) {
System.out.println("ERROR2");
}
try {
String hi = "";
ResultSet rs1 = conexion.getMetaData().getCatalogs();
ResultSetMetaData rsmd = rs1.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++ ) {
hi = hi + rs1.getString(i) + ", ";
}
//for
String sb = hi.substring(0, hi.length()-2);
jTree2.setModel(new FileSystemModel(new File(sb)));
}
}
catch(Exception ae) {
System.out.println("ERROR3");
}
jScrollPane3.setViewportView(jTree2);
And the result I get is this:
Every database is splitted by a "," but I want them to be on a single node for each one. Any help?
This should do it for you:
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases", true);
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rs1.getString(i), true);
parent.add(node);
}
jTree2.setModel(new DefaultTreeModel(parent));
}
actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}
Showing ResultSet exhausted on second time i call this method . First time no error. Showing error at obj[i][j] = rs.getString(1);
public static void createTableModel(ResultSet rs) {
try {
rs.first();
while(rs.next()) {
count++;
}
String [][] obj;
obj = new String [count][3];
rs.first();
for (int i=0; i<count; i++) {
for (int j=0; j < 3; j++) {
if(j == 0) {
obj[i][j] = rs.getString(1);
}
else if(j == 1) {
obj[i][j] = Integer.toString(rs.getInt(2));
}
else if(j == 2) {
obj[i][j] = rs.getString(6);
}
}
rs.next();
}
GlobalVariables.table1 = new DefaultTableModel(obj,
new String [] {
"Name", "Age", "License No"
}
);
}
catch (Exception e) {
e.printStackTrace();
}
}
I converted resultset to an list>
List<ArrayList<String>> result = new ArrayList<>();
do{
ArrayList<String> row = new ArrayList<>(6);
int i = 1;
while (i <= 6) {
row.add(GlobalVariables.data3.getString(i++));
}
result.add(row);
}while (GlobalVariables.data3.next());
It solved the problem. I still don't know why it showed the error exhausted resultset.