Programmer's Blog

Programmer's reference

Category Archives: Java

[Java] Multiple Hash map for hierarchical data

import java.util.*;
import java.lang.*;
import java.io.*;

class myClass
{
 public static void main (String[] args) throws java.lang.Exception
 {
 
 HashMap<Integer, String> inHash = new HashMap<Integer, String>();
 HashMap<Integer, HashMap<Integer, String>> myHash = new HashMap<Integer, HashMap<Integer, String>>();

 inHash.put(1,"Hello");
 myHash.put(1,inHash);
 
 System.out.println(myHash.get(1).get(1));
 }
}

[JDBC] Prepared Statement with HashMap Example

//for demonstration, try catch phrases are removed

public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) {

    PreparedStatement updateSales = null;
    String updateString = "update " + dbName + ".COFFEES " +
                          "set SALES = ? where COF_NAME = ?";

    con.setAutoCommit(false);    //con is java.sql.jdbc.Connection
    updateSales = con.prepareStatement(updateString);

    //Map fields <COF_NAME, SALES>
    for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
            updateSales.setInt(1, e.getValue().intValue());  //SALES
            updateSales.setString(2, e.getKey());   //COF_NAME
            updateSales.executeUpdate();
            con.commit();
     }

     if (updateSales != null) {
          updateSales.close();
     }
     con.setAutoCommit(true);
}

[JDBC] Simple Query Statement

Complete Example for simple statement, note that it is using com.mysql.jdbc Connections from mysql-connector-java (Connector/J)

Configuring class path in windows if you install using a MSI, use the following path:

C:\Progra~2\MySQL\MySQL~1  , where Progra~2 refers to Program Files (x86)

package com.testing.testing;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Statement;
import com.mysql.jdbc.Connection;

public class Testing {
    
        public void getData() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

            Class.forName("com.mysql.jdbc.Driver");
            
            com.mysql.jdbc.Connection conn = null;
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "user", "passwd");
                
            System.out.println("Connected to database");

            //Begin Statement---------------------------------
            Statement stmt = (Statement) conn.createStatement();
            String query = " Select * from mytable";
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next()) {
                
                int id = rs.getInt("ID");
                String name = rs.getString("NAME");
                System.out.println("Record: " + id + " " + name);
            }            
           //End Statement---------------------------------
           conn.close();
}

        public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            
            Testing mytest = new Testing();
            try {        
                mytest.getData();
            } catch (Exception e) 
            {
                System.out.println("SQL ERROR!");
                e.printStackTrace();
            }
        }
}

[JDBC] Connection to MySQL

//mysql-connector-java library is needed
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Statement;
import com.mysql.jdbc.Connection;
public class myclass{

    public Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            com.mysql.jdbc.Connection conn = null;
         
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "user", "passwd");
                
            System.out.println("Connected to database");
            return conn;
        }
    ...
    ... conn.close();
}


/* For setting parametered login, use Properties object

            Properties connectionProps = new Properties();
            connectionProps.put("user", varUser);
            connectionProps.put("password", varPasswd);
            ...
            conn = (Connection) DriverManager.getConnection(varURL, connectionProps);

*/

[Java] Set thread priority

Create Thread object and use setPriority method to rise the value of NORM_PRIORITY parameter

Thread thrd1 = new Thread("High");
Thread thrd2 = new Thread("Low");

thrd1.setPriority(Thread.NORM_PRIORITY+2);
thrd2.setPriority(Thread.NORM_PRIORITY-2);

[Java] Stop all threads when first finishes

1. Firstly declare a static boolean variable to be shared by all threads in the Thread class

class MyThread implements Runnable {
   ..
    static boolean stop = false;
}

2. Then in the run() method set stop to true immediately when loop finishes

public void run() {
    do{
          .....

    } while (stop == false && count < 100);
    stop = true;
}

3. perform checking in other threads for the static boolean, break the loop if stop is true

public void run() {
    do {
        ..
        if (stop == true) then break;
    }
}

[Java] Synchronized Methods

When we use a method inside the thread using synchronize before the method.

synchronized int Method1(int args){
    .......
    return myint;   //method unlocks here 
}

The method will lock until it returns

 

 

[Java] Simple Multithreading

An example code is as follows

class MyThread implements Runnable {

 Thread thrd;

 MyThread(String name) {   //constructor
 thrd = new Thread(this, name);
 thrd.start();
 }

 public void run() {

 try {
   do {
       Thread.sleep(500);
       System.out.println(thrd.getName()); //get threadname

      } while (1);
     } catch(InterruptedException e) {
     System.out.println(thrd.getName() + " interrupted.");
 }
 }

}//class MyThread

public class Test {
 public static void main(String args[]) {

        MyThread mt = new MyThread("Child #1");  //run obj in thrd

 } //main
} //class Test

[javax.swing] Show message box/input box using JOptionPane

In JOption Pane there are mainly 3 types of message boxes,1. information (only got a button of “OK”)

2. Confirmation (asking you for yes/no/cancel)

3. Input box (prompt for input to variables)

javax.swing.JOptionPane;

JOptionPane pane1 = new JOptionPane();

1. JOptionPane.showMessageDialog(pane1 , "hi");
     1st argument: object name
     2nd argument: message

2. JOptionPane.showConfirmDialog(pane1 , "Are you sure?", "Title", 1);
     1st argument: object name
     2nd argument: message
     3rd argument: Title text
     4th argument: button displayed (0 for yes/no, 1 for yes/no/cancel)

3. JOptionPane.showInputDialog 
(Add content later....)

[javax.swing] add and show object to Jframe

JFrame frame1 = new JFrame("Frame");
JButton button = new JButton("OK");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);