Pencarian

Kamis, 26 Desember 2013

CI Multiple Database

CodeIgniter  Multiple database.
Database Postgre
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "postgres";
$db['default']['password'] = "pwdx1";
$db['default']['database'] = "db_postgres";
$db['default']['dbdriver'] = "postgre";
$db['default']['dbprefix'] = "";
$db['default']['port']   = 5432;
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
//Database MySQL
$db['mysqldb']['hostname'] = "localhost";
$db['mysqldb']['username'] = "root";
$db['mysqldb']['password'] = "pwdx2";
$db['mysqldb']['database'] = "db_mysql";
$db['mysqldb']['dbdriver'] = "mysql";
$db['mysqldb']['dbprefix'] = "";
$db['mysqldb']['pconnect'] = FALSE;
Pemanggilan database MySQL di controller :
$this->mysqldb = $this->load->database('mysqldb',TRUE);
$query = $this->mysqldb->query("select *from tabel");
   foreach ($query->result() as $row){
                   }

Pencarian Data di JTable Java

Method ini digunakan untuk melakukan pencarian data pada JTable Java.
public void cari_data(JTable tbl, String text){
        TableRowSorter sorter = new TableRowSorter(tbl.getModel());
        tbl.setRowSorter(sorter);
        sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        tbl.setSelectionMode(1);
}

Java Generate Query Simpan

Jika sebelumnya untuk genereate query update, sekarang generate query simpan
    public static String genQuerySimpan(String tabel,String[] dataValue){
        //generate string untuk query
        String val = "";
        for(int i=0; i < dataValue.length; i++){
            if(i == 0){
                val += "'"+dataValue[i]+"'";
            }else{
                val += ",'"+dataValue[i]+"'";
            }
        }
        String ret = "insert into "+tabel+" values("+val+")";
        return ret;
    }
Untuk menggunakan method static ini :
public static void main(String[] args){            
        String[] data = {"0","budi","123","admin"};
        System.out.println(global_var.genQuerySimpan("tuser", data));
   
    }

Java Generate Query Update

Method static ini digunakan untuk mengGenerate Query Update, jadi nggak repot-repot pake kutip dan +
public static String genQueryUpdate(String tabel, Map data, String kondisi){
       
Map mapData = data;
        String result = "";
        int i=0;
        for (String key : mapData.keySet()) {
                String value = mapData.get( key );
                if(i == 0){
                    result += key+"='"+value+"'";
                }else{
                    result += ","+key+"='"+value+"'";
                }                  
            i++;
         }
        String ret = "update "+tabel+" set "+result+" where "+kondisi;
       return ret;
}
Untuk menggunakannya seperti berikut :
  public static void main(String[] args){              
        HashMap data = new HashMap();
        data.put("username", "budi");
        data.put("hak_akses", "admin");
        System.out.println(global_var.genQueryUpdate("tuser", data, "id_user='2'"));
    }

Java Koneksi ke MySQL

Class JMySQL ini berguna untuk membuka dan menutup koneksi ke database mysql.
package logicClass;
import classtoko.ComboItem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
/**
 *
 * @author a3m-nix
 */
public class JMySQL {
   private static Connection koneksi;
    private Statement stat;
    private ResultSet rs;
    private String query;
    private int row;
    boolean status;  
    String querySave;
    String queryUpdate;
    String queryView;
    String table;
    String field;
    public static String getHostname() {
        return setProgram.getValue("hostname");
    }  
    private static String getUsername() {
        return setProgram.getValue("user");
    }
    private static String getPassword() {
        return setProgram.getValue("password");
    }
    public static String getDbName() {
        return setProgram.getValue("dbname");
    }
   public static Connection getKoneksi(){
        String hostDbDriver = "jdbc:mysql://"+getHostname()+"/"+getDbName();
          try {
            Class.forName("com.mysql.jdbc.Driver");
            koneksi = DriverManager.getConnection(hostDbDriver,getUsername(),getPassword());
          }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Tidak terkoneksi ke database, error konstruktor : "+e);                
             koneksi = null;
          }
         return koneksi;
    }
   public static void main(String[] args) throws SQLException{        
   }
   public static void closeKoneksi(Connection con, Statement st,ResultSet rs){
       try {
           if(con != null){
           con.close();
            }
            if(st != null){
                st.close();
            }
            if(rs != null){
                rs.close();
            }
       } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Close database error "+ex);
       }
   }      
}
Karena method yang digunakan adalah method static maka untuk menggunakan class ini contohnya :

Connection cn = JMySQL.getKoneksi();
       Statement  st = null;
       ResultSet  rs = null;
        try {          
           st = cn.createStatement();
           st.executeUpdate("Disini query SQL");
       } catch (SQLException ex) {
           JOptionPane.showConfirmDialog(null, ex);
       }
       JMySQL.closeKoneksi(cn, st, rs);

Android Client Send and Receive Socket


Sudah lama tidak nulis, sebagai catatan dihari tua:
Bagaimana cara client mengirim data dan menerima hasil dari server menggunakan socket programming.

package com.example.clientserver;import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity{
private EditText txtip, txtport, txtpesan;
private Button btnKirim;
private String inPesan="";
private TextView txtresult;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtip = (EditText) findViewById(R.id.txtip);
        txtport = (EditText) findViewById(R.id.txtport);
        txtpesan = (EditText) findViewById(R.id.txtpesan);
        txtresult  = (TextView)  findViewById(R.id.txtrespone);
        btnKirim = (Button) findViewById(R.id.btnKirim);   //reference to the send button      
    txtresult.setText(inPesan);         btnKirim.setOnClickListener(new View.OnClickListener(){    
      public void onClick(View v) {
     new tcpClient().execute("");
    }
     });    
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }  
   private class tcpClient extends AsyncTask{
String hostname = String.valueOf(txtip.getText());
int    port     = Integer.valueOf(String.valueOf(txtport.getText()));
@Override
protected String doInBackground(String... params) {
 String sentence;
      String modifiedSentence = "";
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
      Socket clientSocket;
try {
clientSocket = new Socket(hostname,port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
   BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
   sentence = String.valueOf(txtpesan.getText());
   outToServer.writeBytes(sentence + '\n');
   modifiedSentence = inFromServer.readLine();
   System.out.println("FROM SERVER: " +modifiedSentence);
   clientSocket.close();
} catch (UnknownHostException e) {
modifiedSentence = "Server error HOST";
e.printStackTrace();
} catch (IOException e) {
modifiedSentence = "Server error IO";
e.printStackTrace();
}    
return modifiedSentence.toString();
}
@Override
protected void onPostExecute(String result) { super.onPostExecute(result);
txtresult.setText(result);
txtpesan.requestFocus();
}    }
}
Inti dari kode diatas, agar android bisa send and receive data, kita bisa menggunakan Class AsyncTask dan mengimplementasikan method doInBackground() dan  onPostExecute()

Senin, 23 Desember 2013

Tugas Lab. Pemrograman Berorientasi Objek

Untuk mahasiswa yang mengontrak perkuliahan Lab. Pemrograman Berorientasi Objek dengan saya, ada sedikit oleh2 untuk liburan akhir tahun yaitu membuat Program Login Menggunakan Java dan Database MySQL. Untuk database Gunakan database dan tabel yang sudah kita bahas di pertemuan sebelumnya.