Jar referencing the Mysql-connector-jav
Configuration file is Database.propertties
1 PackageJdbcdemo;2 3 ImportJava.io.FileInputStream;4 Importjava.io.FileNotFoundException;5 Importjava.io.IOException;6 ImportJava.io.InputStream;7 ImportJava.sql.DriverManager;8 Importjava.sql.PreparedStatement;9 ImportJava.sql.ResultSet;Ten Importjava.sql.SQLException; One Importjava.util.InputMismatchException; A Importjava.util.Properties; - - Importcom.mysql.jdbc.Connection; the Importcom.mysql.jdbc.Statement; - - Public classJdbcutils { - Private voidjdbcutils () {}; + Private StaticString Sqlurl = ""; - Private StaticString SqlUser = ""; + Private StaticString sqlpwd = ""; A Private StaticString classforname = ""; at Private StaticConnection con =NULL; - - Static { - Try { - initconfig (); - Class.forName (classforname); inCon =(Connection) drivermanager.getconnection (Sqlurl, SqlUser, sqlpwd); -}Catch(ClassNotFoundException e) { toSYSTEM.OUT.PRINTLN ("Data-driven failure"); + e.printstacktrace (); -}Catch(SQLException e) { the *SYSTEM.OUT.PRINTLN ("Data connection Failed"); $ e.printstacktrace ();Panax Notoginseng } - } the + Private Static voidinitconfig () { AInputStream inf = jdbcutils.class. getClassLoader (). getResourceAsStream ("Database.propertties"); theProperties Properties =NewProperties (); + Try { - Properties.load (INF); $Classforname = Properties.getproperty ("Driverclass"); $Sqlurl = properties.getproperty ("url"); -SqlUser = Properties.getproperty ("username"); -Sqlpwd = Properties.getproperty ("Password"); the}Catch(IOException e) { -System.out.println ("Failed to read configuration file");Wuyi } the } - Wu Public StaticConnection getconnection () { - returncon; About } $ Public Static voidClose (Connection con,statement Preparedstatement,resultset rs) { - if(Con! =NULL) { - Try { - con.close (); A}Catch(SQLException e) { + //e.printstacktrace (); the } - $ } the if(preparedstatement!=NULL) { the Try { the preparedstatement.close (); the}Catch(Exception e) { - //e.printstacktrace (); in } the } the if(rs!=NULL) { About Try { the rs.close (); the}Catch(Exception e) { the //e.printstacktrace (); + } - } the }Bayi}
Java-jdbc.mysql Tool Class read local file configuration