The primary function of the database connection class is to connect to the database and get the connection object, and close the database. By creating an instance of the class, call the methods in it to avoid repeating the operation.
1 PackageChapter13;2 ImportJava.sql.*;3 Public classDatabaseConnection {4 Private FinalString dbdriver= "Com.mysql.jdbc.Driver";5 Private FinalString dburl= "Jdbc:mysql://localhost:3306/javaweb";6 Private FinalString dbuser= "Root";7 Private FinalString dbpassword= "000000";8 PrivateConnection connection=NULL;9 Publicdatabaseconnection () {Ten Try{ One Class.forName (dbdriver); A This. connection=drivermanager.getconnection (Dburl,dbuser,dbpassword); - } - Catch(Exception e) { theSYSTEM.OUT.PRINTLN ("Load driver failed"); - } - } - PublicConnection getconnection () { + returnconnection; - } + Public voidClose () { A Try{ at connection.close (); - } - Catch(Exception e) { -SYSTEM.OUT.PRINTLN ("Database connection shutdown failed!") "); - } - } in}
JSP database connection class MySQL database