码迷,mamicode.com
首页 > 数据库 > 详细

java APIs for database ------JDBC

时间:2016-05-27 18:01:50      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

# JDBC
# Study Note of JAVA Tutorial
# victor
# 2016.05.27

JDBC helps you to write Java applications that manage these three programming activities:

  1. Connect to a data source, like a database
  2. end queries and update statements to the database
  3. etrieve and process the results received from the database in answer to your query
技术分享
package myjdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

// connect to oracle database
public class dbsession {
    
    private Connection con = null;
    private PreparedStatement pstmt = null;
    private String dburl = null;
    private String username = null;
    private String password = null;
    
    public dbsession(String url,String user,String pass){
        dburl = url;
        username = user;
        password = pass;
    }
    
    private boolean getdbconnection(){
        try {    
            //初始化驱动包     
            Class.forName("oracle.jdbc.driver.OracleDriver");    
            //根据数据库连接字符,名称,密码给 connection 赋值     
            con = DriverManager.getConnection(dburl, username, password);
            return true;
        } catch (Exception e) {   
        e.printStackTrace(); 
        setIs_exception(true);
        setEx(e);
        return false;
        }
    }
    
    private boolean getpreparestatement(String sql){
        try {
            //处理 SQL 语句
            pstmt = con.prepareStatement(sql);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            setIs_exception(true);
            setEx(e);
            return false;
        }
    }
    
    public void execute(String sql){
        if (getdbconnection()){
            sql = sql.toUpperCase();
            System.out.println("execute SQL :: "+sql);
            if(getpreparestatement(sql)){
                if (sql.startsWith("SELECT")){
                    try {
                        ResultSet res = pstmt.executeQuery();
                        setIs_select(true);
                        setResultset(res);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setIs_exception(true);
                        setEx(e);
                    }
                }
                else if(sql.startsWith("INSERT") || sql.startsWith("UPDATE")|| sql.startsWith("DELETE")){
                    try {
                        Integer count = pstmt.executeUpdate();
                        setIs_update(true);
                        setCount(count);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setIs_exception(true);
                        setEx(e);
                    }
                }
                else{
                    setIs_exception(true);
                    setEx(new Exception("other functions are not supported in class dbsession"));
                }
            }
            else{
                System.out.println("prepare sql statement exception!");
            }
        }
        else{
            System.out.println("connect oracle database exception!");
        }
    }
    
    public void printexception(){
        System.out.println("dbsession::"+getEx());
    }
    
    public void printresult() throws SQLException{
        if (isIs_update()){
            System.out.println("update database: "+getCount()+" rows");
        } else if(isIs_select()){
            ResultSetMetaData rsmd = resultset.getMetaData();
            int columnsNumber = rsmd.getColumnCount();
            int rownumber =0;
            //遍历 ResultSet
            while(resultset.next()){
                rownumber ++;
                for(int i = 1;i <= columnsNumber;i++){
                System.out.println("row->"+rownumber+", column->"+i+", selected value is:"+resultset.getString(i));
                }
            }
        }
    }
    
    private boolean is_exception = false;
    private boolean is_update = false;
    private boolean is_select = false;

    private Exception ex = null;
    private Integer count = null;
    private ResultSet resultset = null;
    
    public boolean is_exception_occured() {
        return is_exception;
    }
    private void setIs_exception(boolean is_exception) {
        this.is_exception = is_exception;
    }
    public boolean isIs_update() {
        return is_update;
    }
    private void setIs_update(boolean is_update) {
        this.is_update = is_update;
    }
    public boolean isIs_select() {
        return is_select;
    }
    private void setIs_select(boolean is_select) {
        this.is_select = is_select;
    }
    public Exception getEx() {
        return ex;
    }
    private void setEx(Exception ex) {
        this.ex = ex;
    }
    public Integer getCount() {
        return count;
    }
    private void setCount(Integer count) {
        this.count = count;
    }
    public ResultSet getResultset() {
        return resultset;
    }
    private void setResultset(ResultSet resultset) {
        this.resultset = resultset;
    }
    
    public void close(){
        try {
            if (!(resultset.isClosed())){
                resultset.close();
            }
            if (!(pstmt.isClosed())){
                pstmt.close();
            }
            if (!(con.isClosed())){
                con.close();
            }
            System.out.println("session close successfully!");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

TEST CODE:

技术分享
package myjdbc;

import java.sql.SQLException;

public class Jdbc_Test {

    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub
        dbsession db = new dbsession("jdbc:oracle:thin:@localhost:1522/xe","victor","123");
        db.execute("select sysdate from dual");
        if (db.is_exception_occured()){
            db.printexception();
        }
        else{
            db.printresult();
        }
        db.close();
    }

}
View Code

OUTPUT:

execute SQL :: SELECT SYSDATE FROM DUAL
row->1, column->1, selected value is:2016-05-27 17:16:03.0
session close successfully!

java APIs for database ------JDBC

标签:

原文地址:http://www.cnblogs.com/ct-blog/p/5535446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!