Create basebetter. Java
Package CN. dzj. demo. JDBC; import Java. SQL. *;/*** create Date: 2013-6-24 Author: dzj E-mail: 625065470@qq.com */public class basebetter {public static void main (string [] ARGs) throws classnotfoundexception {// todo auto-generated method stubtry {jdbctemplate ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void jdbctemplate () throws exception {connection conn = NULL; statement STM = NULL; resultset rs = NULL; try {// build connection // conn = jdbcutils. getconnection (); Conn = jdbcutilsingle. getinstance (). getconnection (); // call // create statementstm = Conn. createstatement (); // execute sqlrs = cmd.exe cutequery ("select * from persons;"); // while getwhile (RS. next () {system. out. println (RS. getObject (1) + "," + Rs. getObject (2) ;}} finally {jdbcutils. free (Conn, STM, RS );}}}
Create jdbcutilsingle. Java
Package CN. dzj. demo. JDBC; import Java. SQL. *;/*** create Date: 2013-6-24 Author: dzj E-mail: 625065470@qq.com */public final class jdbcutilsingle {Public String url = "JDBC: mysql: // localhost: 3306/PIMS "; Public String username =" root "; Public String Password =" 123456 "; public static jdbcutilsingle instance = NULL; static {try {class. forname ("com. mySQL. JDBC. driver ");} catch (classnotfoundexception e ){ Throw new exceptionininitializererror (e) ;}} private jdbcutilsingle () {} public static jdbcutilsingle getinstance () {synchronized (jdbcutilsingle. class) {If (instance = NULL) {instance = new jdbcutilsingle () ;}} return instance;} public connection getconnection () throws sqlexception {return drivermanager. getconnection (URL, username, password);} public void free (connection Conn, statement St, resultset R S) {try {If (RS! = NULL) {Rs. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}finally {try {If (st! = NULL) {st. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}finally {try {If (Conn! = NULL) {conn. Close () ;}} catch (sqlexception e) {e. printstacktrace ();}}}}}