Java APIs for database------JDBC

Source: Internet
Author: User

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

JDBC helps-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
 PackageMyjdbc;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;ImportJava.sql.ResultSetMetaData;Importjava.sql.SQLException;//Connect to Oracle database Public classdbsession {PrivateConnection con =NULL; PrivatePreparedStatement pstmt =NULL; PrivateString Dburl =NULL; PrivateString username =NULL; PrivateString Password =NULL;  Publicdbsession (String url,string user,string pass) {Dburl=URL; Username=user; Password=Pass; }        Private Booleangetdbconnection () {Try {                //initializing the driver packageClass.forName ("Oracle.jdbc.driver.OracleDriver"); //assign a value to connection based on the database connection character, name, and passwordCon =drivermanager.getconnection (dburl, username, password); return true; } Catch(Exception e) {e.printstacktrace (); Setis_exception (true);        Setex (e); return false; }    }        Private Booleangetpreparestatement (String sql) {Try {            //working with SQL statementsPSTMT =con.preparestatement (SQL); return true; } Catch(SQLException e) {e.printstacktrace (); Setis_exception (true);            Setex (e); return false; }    }         Public voidexecute (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 blockE.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 blockE.printstacktrace (); Setis_exception (true);                    Setex (e); }                }                Else{setis_exception (true); Setex (NewException ("Other functions is not supported in class Dbsession")); }            }            Else{System.out.println ("Prepare SQL statement exception!"); }        }        Else{System.out.println ("Connect Oracle Database exception!"); }    }         Public voidprintexception () {System.out.println ("Dbsession::" +GetEx ()); }         Public voidPrintresult ()throwssqlexception{if(Isis_update ()) {System.out.println ("Update Database:" +getcount () + "Rows"); } Else if(Isis_select ()) {ResultSetMetaData Rsmd=Resultset.getmetadata (); intColumnsnumber =Rsmd.getcolumncount (); intRowNumber =0; //Traverse ResultSet             while(Resultset.next ()) {RowNumber++;  for(inti = 1;i <= columnsnumber;i++) {System.out.println ("Row->" +rownumber+ ", column->" +i+ ", Selected value is:" +resultset.getstring (i)); }            }        }    }        Private BooleanIs_exception =false; Private BooleanIs_update =false; Private BooleanIs_select =false; PrivateException ex =NULL; PrivateInteger count =NULL; PrivateResultSet ResultSet =NULL;  Public Booleanis_exception_occured () {returnis_exception; }    Private voidSetis_exception (Booleanis_exception) {         This. is_exception =is_exception; }     Public Booleanisis_update () {returnis_update; }    Private voidSetis_update (Booleanis_update) {         This. is_update =is_update; }     Public BooleanIsis_select () {returnIs_select; }    Private voidSetis_select (Booleanis_select) {         This. Is_select =Is_select; }     PublicException GetEx () {returnex; }    Private voidSetex (Exception ex) { This. ex =ex; }     PublicInteger GetCount () {returncount; }    Private voidSetCount (Integer count) { This. Count =count; }     PublicResultSet Getresultset () {returnresultset; }    Private voidSetresultset (ResultSet ResultSet) { This. ResultSet =resultset; }         Public voidClose () {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 blockE.printstacktrace (); }    }}
View Code

TEST CODE:

 PackageMyjdbc;Importjava.sql.SQLException; Public classJdbc_test { Public Static voidMain (string[] args)throwsSQLException {//TODO auto-generated Method StubDbsession db =NewDbsession ("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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.