This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. In this application we have connected to the MySQL database and retrieved the employee names from the database. Here are the JDBC Steps to be followed while writing JDBC program:
我们将链接数据库,执行一个查询,给用户显示数据。 我们使用MySQL 数据库,拿到员工的数据,下面是步骤
* Loading Driver,装载驱动
* Establishing Connection ,建立连接
* Executing Statements,执行Statement 语句
* Getting Results,拿到结果
* Closing Database Connection ,关闭数据库
Before explaining you the JDBC Steps for making connection to the database and retrieving the employee from the tables, we will provide you the structure of the database and sample data.
在我们进行前面步骤前,我们先建立数据库结构和样例数据。
Here is the sql script to create table and populate the table with data:
这里是我们创建表和插入数据的部分
-- Table structure for table `employee`
CREATE TABLE `employee` (
`employee_name` varchar(50) NOT NULL,
PRIMARY KEY (`employee_name`)
);
INSERT INTO `employee` (`employee_name`) VALUES
('Deepak Kumar'),
('Harish Joshi'),
('Rinku roy'),
('Vinod Kumar');
Data inserting in MySQL database table:
插入数据操作的步骤
mysql> insert into employee values('Deepak Kumar');
Query OK, 1 row affected (0.24 sec)
mysql> insert into employee values('Harish Joshi');
Query OK, 1 row affected (0.05 sec)
mysql> insert into employee values('Harish Joshi');
ERROR 1062 (23000): Duplicate entry 'Harish Joshi' for key 1
mysql> insert into employee values('Rinku roy');
Query OK, 1 row affected (0.03 sec)
mysql> insert into employee values('Vinod Kumar');
Query OK, 1 row affected (0.04 sec)
mysql> select *from employee;
+---------------+
| employee_name |
+---------------+
| Deepak Kumar |
| Harish Joshi |
| Rinku roy |
| Vinod Kumar |
+---------------+
4 rows in set (0.04 sec)
Here is the code of java program that retrieves all the employee data from database and displays on the console:
下面是获取元用数据和显示的Java代码
/*
* Import JDBC core packages. Following statement imports the java.sql package, which contains the JDBC core API.
*/
import java.sql.*;
public class RetriveAllEmployees {
public static void main(String[] args) {
System.out.println("Getting All Rows from employee table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbc";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee");
System.out.println("Employee Name: ");
while (res.next()) {
String employeeName = res.getString("employee_name");
System.out.println(employeeName);
}
con.close();
} catch (ClassNotFoundException e) {
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
System.err.println("SQLSTATE: " + ex.getSQLState());
System.err.println("Error code: " + ex.getErrorCode());
ex.printStackTrace();
ex = ex.getNextException(); // For drivers that support chained exceptions
}
}
}
}
Explanation of JDBC Steps:
每一个步骤的解释
- Loading Driver
装载驱动
Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database. The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the
装载驱动是建立数据库JDBC连接的第一步,再尝试连接数据库前,必须装载JDBC的驱动。在JDBC系统装载时,驱动会自动被注册,下面是装载的代码
JDBC driver:
Class.forName(driver).newInstance();
- Establishing Connection
建立连接
In the above step we have loaded the database driver to be used. Now its time to make the connection with the database server. In the Establishing Connection step we will logon to the database with user name and password. Following code we have used to make the connection with the database:
前一步我们已经准备好了数据库驱动来使用。现在我们需要建立数据库连接。我们需要使用用户名和密码来登录数据库,以便建立数据库连接。
con = DriverManager.getConnection(url+db, user, pass);
- Executing Statements
执行语句
In the previous step we established the connection with the database, now its time to execute query against database. You can run any type of query against database to perform database operations. In this example we will select all the rows from employee table. Here is the code that actually execute the statements against database:
我们可以润星各种类型的语句,来让数据库执行操作。这个例子里将读取员工表格的所有行。下面是我们实际执行的语句
ResultSet res = st.executeQuery( "SELECT * FROM employee" ); - Getting Results
获取结果
In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console. Here is the code:
我们已经执行了语句,下面我们从结果集中获取数据,并显示在控制台上。下面是代码
while (res.next()) {
String employeeName = res.getInt( " employee_name " );
System.out.println( employeeName );
}
- Closing Database Connection
关闭数据库连接
Finally it is necessary to disconnect from the database and release resources being used. If you don’t close the connection then in the production environment your application will fail due to hanging database connections. Here is the code for disconnecting the application from database:
最后一步必须关闭连接,释放占用的资源。如果你在正式环境不关闭链接,你将会由于挂起数据库连接而引起错误。下面是关闭数据库连接的代码。
con.close();
In this section you learnt about the JDBC Steps necessary for performing database operations.
这一部分我们学习了JDBC执行数据库操作必须的几个部分。
Output of program:
程序的输出
C:\vinod>javac RetriveAllEmployees.java
C:\vinod>java RetriveAllEmployees
Getting All Rows from employee table!
Employee Name:
Deepak Kumar
Harish Joshi
Rinku roy
Vinod Kumar