1 Importjava.sql.Connection;2 ImportJava.sql.DriverManager;3 ImportJava.sql.ResultSet;4 Importjava.sql.Statement;5 Importjava.util.Date;6 7 8 Public classNewinstanceexample {9 Ten Public Static voidMain (string[] args)throwsException { One //Class.forName () requires the JVM to find and load the specified class A //newinstance () Gets an instance of the class - //newinstance () method differs from the New keyword: one is a method, one is a keyword, and newinstance () can only call a parameterless constructor - //forname and newinstance gain greater flexibility and provide a means of decoupling theDate date = Java.util.Date.class. newinstance (); - LongTime =date.gettime (); - System.out.println (time); - +class<?> Dateclass = Class.forName ("Java.util.Date"); -Date Date2 =(Date) dateclass.newinstance (); + LongTime2 =date2.gettime (); A System.out.println (time2); at - mysqlconnection (); - - } - - Public Static voidMysqlconnection ()throwsException { in //It is explicitly required in the JDBC specification that the driver class must register itself with DriverManager - //similar to the following: to /* + Public class Myjdbcdriver implements Driver { - Static { the Drivermanager.registerdriver (New Myjdbcdriver ()); * } $ }Panax Notoginseng */ - //Class.forName () executes a static block of code when the Com.mysql.jdbc.Driver is loaded, registering itself with DriverManager theClass.forName ("Com.mysql.jdbc.Driver"); +String url = "Jdbc:mysql://localhost/test?useunicode=true&&characterencoding=utf-8&autoreconnect=true "; AString user = "root"; theString password = "123456"; + -Connection conn =NULL; $Statement stmt =NULL; $ResultSet rs =NULL; - Try { -conn =drivermanager.getconnection (URL, user, password); thestmt =conn.createstatement (); -String sql = "Select Deptno,deptname from dept";//Dept This table has a deptno,deptname fieldWuyirs = stmt.executequery (SQL);//Execute SQL statement the while(Rs.next ()) { -System.out.print (Rs.getint ("deptno") + ""); WuSystem.out.println (rs.getstring ("Deptname")); - } About}Catch(Exception e) { $ Throwe; -}finally { - rs.close (); - stmt.close (); A conn.close (); + } the } -}
Class.forName () and newinstance ()