jdbc connect to the database (change)

package org.craf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FilterData {
        private Connection dbConnection = null;
    private Statement selectPro = null; //  Used to select operation  
    private Statement updatePro = null; //  For update operations  
    private ResultSet dbResultSet = null; //  Operating select the result set  
    
    private String driverName;//  MySql driver class declaration  
    private String dbHost;
    private String dbPort;
    private String dbName;
    private String dbUserName;
    private String dbPassword;
    private String enCoding; 
    
    /** *//**
     *   DbConnection object instantiation  
     * @param host   Database Host  (IP)
     * @param port   Database port  
     * @param dName   Database Name  
     * @param uName   Username  
     * @param password   Password  
     */
    public FilterData(String host, String port, String dName, String uName, String password)
    {
        driverName = "com.sybase.jdbc3.jdbc.SybDriver";
        dbHost = host;
        dbPort = port;
        dbName = dName;
        dbUserName = uName;
        dbPassword = password;
        enCoding = "?Charset";
    }//end DbConnection()
    
    /** *//**
     *   Connect to the database  
     * @return  Connection successful return true, the connection fails to return  false
     */
    public boolean dbConnection()
    {
        StringBuilder urlTem = new StringBuilder();
        urlTem.append("jdbc:sybase:Tds:");
        urlTem.append(dbHost);
        urlTem.append(":");
        urlTem.append(dbPort);
        urlTem.append("/");
        urlTem.append(dbName);
        urlTem.append(enCoding);
        String url = urlTem.toString();
        try
        {
            Class.forName(driverName).newInstance();
            dbConnection = DriverManager.getConnection(url, dbUserName, dbPassword);
            return true;
        }catch(Exception e){
            System.err.println("  Database connection failed  !");
            System.out.println("url = " + url);
            e.printStackTrace(); //  Detailed error message received  
            return false;
        }
    }// end dbConnection()
    
    /** *//**
     *   Select the implementation of special operations  ,  Note  :  SelectSql the field and in the  fields  In number. Name to be consistent  
     * @param selectSql   For the implementation of the select statement  
     * @param fields   To select the field  
     * @return   Map of containing  ArrayList,  A record form a  Map
     */
    public ArrayList dbSelect(String selectSql, ArrayList fields)
    {
        ArrayList<Map> selectResult = new ArrayList<Map>();
        Map<String, String> recordInfo;
        try{
            selectPro = dbConnection.createStatement();//  Statement object definitions  
            dbResultSet = selectPro.executeQuery(selectSql);
            while(dbResultSet.next()){
                recordInfo = new HashMap<String, String>();
                for(int i = 0; i<fields.size(); ++i)
                    recordInfo.put((String)fields.get(i), dbResultSet.getString((String)fields.get(i)));
                selectResult.add(recordInfo);
            }
            dbResultSet.close(); //  Disconnect the result set  
            selectPro.close(); //  Disconnect the Statement object  
        }catch(Exception e){
            System.out.println("  Select operation failed  ");
            System.out.println("Sql = " + selectSql);
            e.printStackTrace();
        }
        return selectResult;
    }//end dbSelect()
    
    /** *//**
     *   Performed on the database update, delete or  insert  Operation 
     * @param sql   SQL statement to perform the operation  
     * @return   The implementation of successful return true, failure to return  false
     */
    public boolean dbUpdate(String sql)
    {
        try
        {
            updatePro = dbConnection.createStatement(); //  Statement object definitions  
            updatePro.executeUpdate(sql);
            updatePro.close();// -------------  Close the Statement object  
            return true;
        }catch(Exception err){
            System.out.println("  Database operation failed  !");
            System.out.println("Sql = " + sql);
            err.printStackTrace();
            return false;
        }
    }//end dbUpdate()
    
    /** *//**
     *   Close the database connection  
     * @return   Successful return true, failure to return  false
     */
    public boolean closeDatabase()
    {
        try{
            if(dbConnection != null)
                dbConnection.close();
            return true;
        }catch (Exception ex){
            ex.printStackTrace();
            return false;
        }
    }//end closeDatabase()
    
    public String filterData(String area){
        String areas[] = area.split("-");
        String resultData = "";
        if(areas.length == 3){
                resultData = areas[0]+"-"+areas[2];
        }else{
                resultData = area;
        }
        return resultData;
    }
    
    public static void main(String[] args)
    {
        String dbHost = "192.168.0.57";
        String dbPort = "5000";
        String dbName = "ssjg";
        String dbUserName = "sa";
        String dbPassword = "123456";
        String tableName = "BASEDATA_50000011";
        String tableid = "BASEDATAID";
        String areaname = "JCDQNAME";
        FilterData conn = new FilterData(dbHost, dbPort, dbName, dbUserName, dbPassword);
        boolean bool = conn.dbConnection();
        if(!bool)
            return;
        String selectSql = "select "+tableid+","+areaname+" from "+tableName+" order by JCDID";
        ArrayList<String> fieldsList = new ArrayList<String>();
        fieldsList.add(tableid);
        fieldsList.add(areaname);
        ArrayList<Map> userInfoList = conn.dbSelect(selectSql, fieldsList);
        int infoSize = userInfoList.size();
        String userName;
        String ad;
        if(infoSize == 0)
            System.out.println("  No data selected eligible  ");
        else{
            for(int i = 0; i < infoSize; ++i){
                userName = (String)userInfoList.get(i).get(areaname);
                ad = (String)(((Map)userInfoList.get(i)).get(tableid));
                String areaData = conn.filterData(userName);
                String updateSql = "update "+tableName+" set "+areaname+" = '" + areaData + "' where "+tableid+" ="+new Integer(ad)+"";
                conn.dbUpdate(updateSql);
                System.out.println(areaname + " = " + areaData+";"+tableid+" = " + ad);
            }
            System.out.println("  Total number of records  :"+infoSize);
        }
        conn.closeDatabase();
    }//end main()
    


}
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of jdbc connect to the database (change)

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • can not be represented as java.sql.Timestamp

    Development of procedures for the use of hibernate when, some time there is no need to fill in the fields, but after the hibernate query time reported "Java.sql.SQLException: Value'0000-00-00 'can not be represented as java.sql.Timestamp ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Hibernate annotation using notebook

    These are the basic common @Entity --Declared an entity bean @Table(name="promotion_info") --For the entity bean mapping for the specified table (Table name ="promotion_info) @Id --Declare that the identifying attribute of the entity bean @GeneratedValue

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries