Statement: The material used in this column is written by the VIP students of the Kay Academy, who has the right to be anonymous and has the final right to interpret the article; The Edith Academy is designed to promote students to learn from each other on the basis of public notes.
JDBC Comprehensive Example
This comprehensive example is the use of JDBC to the database table to increase, delete, check, change operations, which also have to test each of these methods, so also write test cases. The main significance of writing this example is to practice and further familiarize yourself with JDBC's way of adding, deleting, checking, and modifying database tables to solidify this knowledge point.
The techniques used in this example are: Maven, DBUnit, c3p0 connection pool, log4j, MySQL database.
1. Prepare a clean database and two tables, and build an association relationship for the two tables:
2. Create a MAVEN project and configure all of the dependent packages:
Configure the Dependent packages:
3. Create the appropriate package in the source folder and the test source folder to classify it so that all classes are cluttered together:
Packages under the source folder:
C3p0manager This package is used to put the Connection object management class
Org.zero01.iuds This package is used to encapsulate classes and function classes.
Exception This package is used to put the custom exception class
Test the package under the source folder:
Org.zero01.test This package is used to put the test case class
4. Create a class under the C3p0manager package that is used to obtain the database connection object through the C3P0 connection pool, and this class is a singleton pattern:
code example:
5. Write data encapsulation classes for two tables:
CLS code example:
Student code Example:
6. Write a functional class for CLS table operations:
7. Write the function class for the student table operation:
8. Write the test class in the Org.zero01.test package under the Test source folder and test the methods of the two function classes individually:
Test results:
Test coverage:
Print the log information:
Hint: I This is the finished code, but you actually write the code, it is best to write a method to test, do not write all the function code and then write test case test, because that if there is a problem, many places of code to be modified, if you write a method to test a method, You just need to make changes to one method, and other methods do not need to change, so it is more efficient and easy to modify the code, do not have to modify the changes everywhere to dazzle.
When I was writing the C3p0manager class, I made a small logical mistake, and this error was recorded here because I declared the properties of the build object in front of the C3P0 data source class variable. A null pointer exception is thrown when the Getconnection method is used in the constructor's outward:
Graphic:
The correct way to declare:
JDBC Comprehensive Example