In the previous blog, "Learning from the JDBC Operations Database (1)" In Example 1, we have learned how a Java application can process a database through JDBC in a program, but we have also said that such an example is not available in the actual development, This article is in the simple development of how to "upgrade" the previous example, to meet the simple development of database additions and deletions (CRUD).
If you follow the example in the previous article, then we do add and remove changes will appear in each method to get the connection, release resources, the code will appear very large repetition, so we should each add and remove changes to each method can be reused code extracted, at the same time in order to be able to switch the database convenient, It is also time to define some of the configuration information separately in the configuration file instead of writing to the program.
Example 1:
The data definition in the database:
//Create a libraryCreate DatabaseJdbcdemo; //Use the library UseJdbcdemo; //Create a user tableCreate Table User(IDint Primary Key, namevarchar( +), ageint );
create the project and write the configuration information file:
Create a project, import the database-driven jar package, and create a new database.properties file in the "src" directory:
The contents of the Database.properties configuration file are as follows:
Driver=com.mysql.jdbc.driver url=jdbc:mysql://localhost:3306/jdbcdemo username=root password=root
Writing Database Tools class Jdbcutils
Regardless of the method in a project to operate the database before, it is necessary to ensure that the driver manager has a database driver, get connections, release resources, some of these operations are executed once, some are repeated to be called, so using a tool class to encapsulate is the most suitable.
1 Public classJdbcutils {2 3 Private StaticProperties config =NewProperties ();4 5 Static{6InputStream in = Jdbcutils.class. getClassLoader (). getResourceAsStream ("Database.properties");7 Try{8 config.load (in);9Class.forName (Config.getproperty ("Driver"));Ten One A}Catch(Exception e) { - Throw NewExceptionininitializererror (e); - } the } - - Public StaticConnection getconnection ()throwsSQLException { -String url = config.getproperty ("url"); +String username = config.getproperty ("username"); -String Password = config.getproperty ("Password"); +Connection conn =drivermanager.getconnection (URL, username, password); A returnConn; at } - - Public Static voidrelease (Connection conn,statement st,resultset rs) { - if(rs!=NULL) { - Try{ - rs.close (); in}Catch(Exception e) { - e.printstacktrace (); to } + } - if(st!=NULL) { the Try{ * st.close (); $}Catch(Exception e) {Panax Notoginseng e.printstacktrace (); - } the } + if(conn!=NULL) { A Try{ the conn.close (); +}Catch(Exception e) { - e.printstacktrace (); $ } $ } - } -}
View Code
In this tool class, because the information to load the database from the configuration file and the drive to register the database with reflection to the drive manager is only needed once throughout the engineering application, write these functions using static blocks of code. Depending on the same Property object, the database information is saved so that the method in which the tool class obtains the connection can provide a URL, user name, and password information for each invocation in the Getconnection method. In addition, as a tool class, the methods in this class are best static.
You can see that if an exception occurs in the Jdbcutils tool class, then I am directly transitioning to a exceptionininitializererror error because the database is the most critical part of the underlying error, then the application should not be executed, Of course, to throw an exception or error can be selected according to individual or situation.
This tool class just makes the simplest registered drive, gets the connection and frees up resources, and can add other practical methods to the tool class as needed in real-world development.
to add and revise a database:
The tool class is written in the front, then we in some classes of methods to operate the database, then you can get the method from the tool class, and then write their own business logic operation and then use the tool class method for resource release.
1 Public classDemo {2 3 Public voidInsert ()throwsSQLException {4Connection conn =NULL;5Statement st =NULL;6ResultSet rs =NULL;7 Try{8conn = Jdbcutils.getconnection ();//Get Connections9St =conn.createstatement ();TenString sql = "INSERT into user (Id,name,age) value (1, ' Ding ', 25)"; One intnum =st.executeupdate (SQL); A if(num>0) { -SYSTEM.OUT.PRINTLN ("Data added successfully!")); - } the}finally{ -Jdbcutils.release (Conn, St, RS);//Freeing Resources - } - } +}
View Code
This is only shown in the demo to add data to the database operation, modification and deletion is only different on the SQL statement, and if the query will return the result set ResultSet object, in the previous article in Example 1 and Example 2 has been explained, this is no longer described here. In the general web development, we will change the database additions and deletions on the DAO layer.
This article to the database additions and deletions as an example, mainly to describe how to create a tool class, and in the tool class to register the database driver, write a practical way to get the connection and release resources static methods, these are in my opinion more useful design ideas.
Learning from the JDBC Operations Database (2)