JDBC additions and deletions are rewritten into a method that invokes a tool class

Source: Internet
Author: User

 Packagecom.hx.jdbc.connection;Importjava.sql.Connection;Importjava.sql.Statement;ImportCom.mysql.jdbc.UpdatableResultSet;Importjunit.framework.TestCase; Public classJdbctextextendsTestCase {/*** Create a Insert,update,delete common method *@paramSQL*/     Public voidupDate (String sql) {Connection conn=NULL; Statement Statement=NULL; Try{conn=Jdbctools.getconnection2 ();//Call the GetConnection2 () method in the tool class to complete the database connection statement=conn.createstatement (); Statement.executeupdate (SQL);//Execute SQL statement}Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{JDBCTOOLS.GUANBI (statement, conn);//Call the Guanbi () method in the tool class to finish closing statement and Conn} }

The above is a JDBC Access database that adds, modifies, and removes common methods. Where the database connection is completed and the database is closed, the duplicate and universal operation is written in the tool class Jdbctools.java, as follows:

 Packagecom.hx.jdbc.connection;ImportJava.io.InputStream;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.util.Properties; Public classJdbctools {/*** This is a way to connect to the database and put it in this tool class *@return     * @throwsException*/     Public StaticConnection GetConnection2 ()throwsexception{//1. Create 4 strings for a database//2. Create a Properties ObjectProperties properties=NewProperties (); //3. Get the input stream corresponding to the Jdbc.proInputStream in=Jdbctools.class. getClassLoader (). getResourceAsStream ("Com/hx/jdbc/connection/jdbc.properties");
Focus here on ******
//**********************
Because I made a mistake, ******.
//**********************
System.out.println (in);//When I error the above line code null pointer exception, here print in, output null,
Know the above code does not have access to the Jdbc.properties configuration file, I began to write directly jdbc.properties
Jdbc.properties should be written under the root directory.//4. Loading the input streamproperties.load (in); //5. Determine the value of 4 stringsString driver=properties.getproperty ("Driver"); String Jdbcurl=properties.getproperty ("Jdbcurl"); String User=properties.getproperty ("User"); String Password=properties.getproperty ("Password"); //6. Load the database driverClass.forName (driver); //7. Get the database connection through the DriverManager getconnection () methodConnection conn=drivermanager.getconnection (jdbcurl, user, password); returnConn; }
/**
* This is the tool to close the database, because it is necessary to use the deletion, so write in this tool method
*/
Public Static voidGuanbi (Statement statement,connection conn) {if(statement!=NULL){ Try{statement.close (); } Catch(Exception E2) {//TODO auto-generated Catch blockE2.printstacktrace (); } } if(conn!=NULL){ Try{conn.close (); } Catch(Exception E2) {//TODO auto-generated Catch blockE2.printstacktrace (); } } }}

I made a mistake in the tool code above, and the reason for the error is as follows:

The first way to load a resource file with a class is to have the following three kinds: (Package structure diagram)

1) inputstreaminstream=daofactory.class.getresourceasstream ("Dao.properties");

? 2) Instream=daofactory.class.getresourceasstream ("/com/jdbc/dao/dao.properties")

3) Instream=daofactory.class.getclassloader (). getResourceAsStream ("com/jdbc/dao/dao.properties");

The first and second way is to use the class object to load, the third uses the ClassLoader object to load the resource file, The reason a class object can also load a resource file is because the class class encapsulates the ClassLoader getResourceAsStream method. From the source code in class, you can see:

?? This is no doubt convenient for the client's call, save every time to get ClassLoader to load the resource file trouble.

Path problem:

1. The third is the most essential approach, and the first two are also based on the third kind of implementation. The JVM will cause Bootstraploader to load the resource file. So the path is still this relative to the engineering root directory that is "Com/jdbc/dao/dao.properties" (No Need "/").

2. The first is the relative path used, where the resource file is compared to the position of the current class (Daofactory Class), and this way the class object does some processing. This method is Reslovename (name). The final name will still be converted to the name parameter for the third Way

3. The second is the absolute path, the absolute path is relative to the Classpath root directory path (the project SRC directory corresponding to the bin directory (the directory that holds the. class file)).

And then here's my jdbc.properties configuration file.

Driver=com.mysql.jdbc.driver
Jdbcurl=jdbc:mysql://localhost:3306/students
User=root
password=5678

The following is a call to the update () method for the add-and-revise operation:

 package   com.hx.jdbc.connection;  public  class   Test { public  static  void   main (string[] args) {String sql  = "INSERT into T_student (name,age,email) VALUES        (' 78878 ', ' a ', ' 999999999 ') ";  // string sql= "DELETE from T_student where        Id=3 ";  // string sql= "UPDATE t_student set Name= '        66666 ', age= ', email= ' where id=3 ';         Jdbctext j=new   Jdbctext ();    J.update (SQL); }}

JDBC additions and deletions are rewritten into a method that invokes a tool class

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.