JDBC programming and jdbc

Source: Internet
Author: User

JDBC programming and jdbc
I. Overview 1. Why JDBC?

The database is an indispensable part of the program. Every website and server requires a database. For most application programmers (this does not include database developers), we do not operate databases in DBMS, but access databases in the programs we write, in Java programs, JDBC is usually used to connect to the server and perform addition, deletion, modification, and query operations. Next, we will introduce JDBC programming in detail.

2. SQL language classification

Structured Query Language SQL is divided into three types based on different types of operations:

(1) DQL: Data Query Language example: select

(2) DML: data manipulation language example: insert, update, delete

(3) DDL: Data Definition Language example: create

2. preparations required for JDBC programming 1. Development Environment preparation

First, configure the integrated development environment. In this example, the IDE is MyEclipse2014 and the database is MySQL. Before programming, we must first reference the jar package officially provided by MySQL. This package provides the database driver. loading the database driver is an indispensable step in JDBC programming.

To reference a jar package (in MyEclipse ):

(1) create a lib folder in the project path

(2) download the jar package and copy it to the lib folder.

(3) Right-click the jar package imported to the lib folder, select Build Path, add it to Build Path, and add it to reference list

After configuring the integrated development environment and introducing the MySQL jar package, we can start our JDBC programming.

2. Database preparation

We have created a WORKER table for storing employees. The table creation statement is as follows:

1 create table WORKER (2     worker_num varchar(10),3     worker_name varchar(20) not null,4     worker_dept int(3),5     worker_address varchar(50),6     worker_sal int(5),7     worker_level varchar(10),8     constraint pk_worker_num primary key(worker_num),9 );

 

3. Write the first JDBC Program

1. JDBC programming process:

(1) load the database driver

A database driver is a set of classes that implement JDBC interfaces for specific databases. When preparing, we loaded the jar package corresponding to the mysql database, which contains the database driver. Only when the database driver is loaded can operations on the Database continue.

1 // The code for loading the database Driver is as follows 2 Class. forName ("com. mysql. jdbc. Driver ");

The parameters of the forName method are determined by different databases. Here we load the MySQL database driver.

(2) define the url of the database (Uniform Resource Locator)

A url is a required element for obtaining a connection. Its format is as follows: Protocol, IP address, port number, and database name.

The url we define is as follows:

String url = "jdbc: mysql: // localhost: 3306/mydb? UseUnicode = true & amp; characterEncoding = UTF-8"

Among them, jdbc: mysql is the protocol part; localhost is the IP address, here is the local machine; 3306 is the default port number of MySQL; mydb is the database name; the role of the following part of the question mark is to prevent garbled characters.

(3) obtain the Connection object of the database)

To perform operations on the database, first obtain the database connection object. In JDBC, we use the DriverManager static method to initialize the connection object.

1 // The code for obtaining the database Connection object is as follows: 2 Connection conn = DriverManager. getConnection (url, userName, passWord );

The getConnection method has three String-type parameters: database connection url, database login username, and database login password.

(4) Create and initialize Statement

Statement is used to execute statements. We use the built-in method of Connection to initialize Statement, and then execute SQL statements through the Statement object.

// The code for creating a Statement object is as follows: Statement stmt = conn. createStatement ();

Here, conn is the obtained Connection object.

(5) Execute SQL statements

(6) release database resources

Database resources are limited. If the connection object is never released, once the upper limit is reached, the subsequent application cannot obtain the connection object and the program cannot be executed. Similarly, the Statement object occupies the memory. Once the memory is used up, the execution of the program is blocked. Therefore, we need to disable these objects each time.

2. An example of DQL operations on the database
1 // connect to the database and query 2 public class JdbcTest {3 public static void main (String [] args) {4 String url = "jdbc: mysql: // localhost: 3306/mydb? UseUnicode = true & amp; characterEncoding = UTF-8 "; 5 String user =" root "; 6 String psw =" root "; 7 String SQL =" select * from WORKER "; 8 Connection conn = null; 9 Statement stmt = null; 10 ResultSet rs = null; 11 try {12 Class. forName ("com. mysql. jdbc. driver "); 13 conn = DriverManager. getConnection (url, user, psw); 14 stmt = conn. createStatement (); 15 rs = stmt.exe cuteQuery (SQL); 16 while (rs. next () {17 String workerNumber = rs. getString ("worker_num"); 18 System. out. println (workerNumber); 19} 20 21} catch (ClassNotFoundException e) {22 e. printStackTrace (); 24} catch (SQLException e) {25 e. printStackTrace (); 26} finally {27 try {28 stmt. close (); 29 conn. close (); 30} catch (SQLException e) {31 e. printStackTrace (); 32} 33} 36} 37}

The ResultSet is a result set object used to receive the query results. Finally, the queried data is obtained from the result set for output.

Iv. Improvements to JDBC programming 1. Separating configuration files from programs

The abstract method of the tool class is to abstract a piece of code that needs to be executed multiple times to form a tool method. In addition to this improvement, the JDBC program can also use the configuration file to separate the configuration information from the Program (this method is called soft encoding ), in this way, you can avoid modifying the program when modifying the configuration information, resulting in a large number of re-tests of the program.

Common configuration files include. xml files and. properties files. The configuration we need here is a few two-dimensional basic strings, so we can use the. properties file for configuration.

The configuration file is as follows:

1 #db.properties2 driver = com.mysql.jdbc.Driver3 url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-84 username = root5 password = root

 

2. encapsulation of reusable code

When you think about the execution process of the JDBC program, you will find that many operations need to be performed every time you connect to the database: if several database classes need to be connected to the same database and perform data operations on them, we can abstract the functions of the Connection object to form a separate tool class. The details are as follows:

 

1 // compilation of tool Classes 2 public class JDBCUtils {3 private static String driverClass; 4 private static String url; 5 private static String userName; 6 private static String passWord; 7 static {
// Read the resource file 8 Properties p = new Properties (); 9 try {10 p. load (JDBCUtils. class. getResourceAsStream ("db. properties "); 11} catch (IOException e) {12 e. printStackTrace (); 13} 14 driverClass = p. getProperty ("driver"); 15 url = p. getProperty ("url"); 16 userName = p. getProperty ("username"); 17 passWord = p. getProperty ("password"); 18 try {19 Class. forName (driverClass); 20} catch (ClassNotFoundException e) {21 e. printStackTrace (); 22} 23} 24 public static Connection getConnection () {25 Connection conn = null; 26 try {27 conn = DriverManager. getConnection (url, userName, passWord); 28} catch (SQLException e) {29 e. printStackTrace (); 30} 31 return conn; 32} 33 public static void closeAll (ResultSet result, Statement stmt, Connection conn) {34 try {35 result. close (); 36} catch (SQLException e) {37 e. printStackTrace (); 38} 39 try {40 stmt. close (); 41} catch (SQLException e) {42 e. printStackTrace (); 43} 44 try {45 conn. close (); 46} catch (SQLException e) {47 e. printStackTrace (); 48} 49} 50 public static void closeAll (PreparedStatement stmt, Connection conn) {51 try {52 stmt. close (); 53} catch (SQLException e) {54 e. printStackTrace (); 55} 56 try {57 conn. close (); 58} catch (SQLException e) {59 e. printStackTrace (); 60} 61} 62}

In the compilation of tool classes, we use the static block. Here, the static block contains only the class that needs to be executed when the class is loaded. At the same time, we set the tool method to a static method, easy to call.

3. Improved JDBC Program
 1 public class NewGetWorker { 2     public static void main(String[] args) { 3         Connection conn = null; 4         Statement stmt = null; 5         ResultSet result = null; 6         String sql = "select * from WORKER"; 7         conn = JDBCUtils.getConnection(); 8         try { 9             stmt = conn.createStatement();10             result = stmt.executeQuery(sql);11             while(result.next()) {12                 String workerNum = result.getString("worker_num");13                 String workerName = result.getString("worker_name");14                 String workerAddress = result.getString("worker_address");15                 String workerLevel = result.getString("worker_level");16                 System.out.println(workerNum + " " + workerName + " " + workerAddress + " " + workerLevel);17             }18         } catch (SQLException e) {19             e.printStackTrace();20         }finally {21             JDBCUtils.closeAll(result, stmt, conn);22         }23         24     }25 }

From the improved program, we can directly call the method in the tool class to obtain the connection object, and call the close method of the tool class in the finally block to close the object, this effectively increases code reusability.

V. Summary

JDBC is a set of Apis provided by Java to connect to databases. Using these Apis can meet the needs of connecting Java programs to the database in daily development. The content of JDBC is far from the introduction of this blog, and there is still a lot of follow-up knowledge. I believe that after reading this blog post, you will have a preliminary understanding of the compilation of the JDBC program. More articles will be written in the future.

Ps. Bloggers are also cainiao on their way to learning. If you want to learn together, please contact us.

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.