数据库 —— 使用JDBC操作数据库

[Link] http://www.developer.com/java/data/manipulating-a-database-with-jdbc.html

Manipulating a Database with JDBC

Java programs communicate with the database and manipulate its data with the help of the JDBC API. The JDBC driver enables the Java application to connect to a database. JDBC is almost always used with relational databases, also it can be used with any other table based data source. We do not have to worry about the availability of a driver, as major RDBMS (Relational Database  Management System) providers provide them free. Apart from that there are many third-party JDBC drivers available.


Basic Requirements

Since we shall be going hands on down the line, the basic software requirements for JDBC programming are as follows.

1.Java SDK

  

Magic Quadrant for Enterprise Application Platform as a Service, Worldwide

Download Now

2.RDBMS Package (For example, MySQLOraclePostgreSQL, etc.)

3.IDE (For example, EclipseNetBeansJDeveloper, etc.)

4.JDBC driver (JDBC drivers are database specific, especially, if we use a driver other than Type1:JDBC-ODBC Bridge. For example, MySQL Connector/Jis the official JDBC driver for MySQL, ojdbc for Oracle and so on...PostgreSQL JDBC Driver)

Installation is pretty straightforward; if in doubt, refer to the appropriate installation instruction of the relevant packages during installation.

JDBC Programming Steps

Every Java code in JDBC Programming goes through the following six steps in one way or the other. These steps give an idea about what order to follow during coding and a basic insight into their significance.

Related Articles

1. Importing java.sql Package

Almost all the classes and interfaces used in JDBC programming are compiled in the java.sql package. As a result it is our primary requirement to import the package as follows.

import java.sql.*;

2. Load and Register JDBC Driver

The most common and easiest way to load the driver is by using the Class.forName() method.

Class.forName("com.mysql.jdbc.Driver");

This method takes the complete package name of the driver as its argument. Once the driver is loaded, it will call the DriverManager.registerDriver() method to register itself. Registering a driver implies that the currently registered driver is added to a list of available Driver objects maintained by the DriverManager. The driver manager serves the request from the application using one of the lists of available Driver objects.

3. Establishing Connection

The standard method to establish a connection to a database is through the method callDriverManager.getConnection(). The arguments accepted by this method are: a string representation of the database URL, the user name to log in to the database and the password.

DriverManager.getConnection("jdbc:mysql://localhost/hr","user1","pass");

4. Creating a Statement

We need to create a Statement object to execute a static SQL query. Static SQL statements can be updates, inserts, queries and even DDL SQL statements. Statement objects are created  with the help of the Connection object‘s  createStatement() method as follows:

Statement statement = connection.createStatement();

5. Execute SQL Statement and Retrieve Result

We can use the executeQuery() method of the Statement object to fire the query to the database. This method takes an SQL query string as an argument and returns the result as a ResultSetobject. The ResultSet object contains both the data returned by the query and methods for retrieving the data.

ResultSet resultSet=statement.executeQuery("SELECT
* FROM employees");

The get methods of the ResultSet object can be used to retrieve each of the fields in the record fetched from the database into java variables.

while(resultSet.next()){
      System.out.println(resultSet.getString(“emp_id”));
      System.out.println(resultSet.getString(“first_name”));
      System.out.println(resultSet.getString(“last_name”));
      ...
      }

6. Close Connection

It is highly recommended that an application should close the Connection object and Statementobjects explicitly, because, earlier opened connections can cause trouble for the database and open connections are also prone to security threats. Simply add following statements:

statement.close();
connection.close();

Putting it Together

Let us create an application to demonstrate the CRUD operation to manipulate the database records. CRUD stands for CreateReadUpdate and Delete. We shall fetch the database record with a Readoperation, create a new record and save it into the database with a Create operation, modify the existing record with an Update operation and remove a record from the database with a Deleteoperation. Observe that the code below is self-explanatory and almost repetitive with a few significant lines actually invoking the change in the operation. To get a deeper grasp on the Java SQL library functions, refer to the Java API documentation.

//import statements...

public class Main {

       private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
       private static final String DATABASE_URL = "jdbc:mysql://localhost/hr";
       private static final String USERNAME = "admin";
       private static final String PASSWORD = "secret";

/* This operation creates the table in the database which otherwise have to be created through SQL DDL. This operation is given for convenience and does not belong to the CRUD operation we are talking of. Nonetheless novice programmer may find it useful as of how to create a table through Java code...*/

       public static void createTable(){
             Connection connection = null;
             Statement statement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
                                  PASSWORD);
                    statement = connection.createStatement();
                    //boolean b=statement.execute("DROP TABLE IF EXISTS emp");
                    boolean b=statement.execute("CREATE TABLE                         emp(id int primary key,name varchar(15),department int,salary int,location varchar(20))");
                    if(b==true)
                           System.out.println("Tables created...");
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           statement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void createEmployee(int id, String name, int dept, int sal, String loc){
             Connection connection = null;
             PreparedStatement preparedStatement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,PASSWORD);
                    preparedStatement = connection.prepareStatement("INSERT INTO emp VALUES(?,?,?,?,?)");
                    preparedStatement.setInt(1, id);
                    preparedStatement.setString(2, name);
                    preparedStatement.setInt(3, dept);
                    preparedStatement.setInt(4, sal);
                    preparedStatement.setString(5, loc);
                    boolean b=preparedStatement.execute();
                    if(b==true)
                           System.out.println("1 record inserted...");
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           preparedStatement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void updateSalary(int id, int raise){
             Connection connection = null;
             PreparedStatement preparedStatement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,PASSWORD);
                    preparedStatement = connection.prepareStatement("UPDATE emp SET salary=salary+? WHERE id=?");
                    preparedStatement.setInt(1, raise);
                    preparedStatement.setInt(2, id);
                    boolean b=preparedStatement.execute();
                    if(b==true)
                           System.out.println("$"+raise+" raised for emp id="+id);
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           preparedStatement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void deleteEmployee(int id){
             Connection connection = null;
             PreparedStatement preparedStatement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,PASSWORD);
                    preparedStatement = connection.prepareStatement("DELETE FROM emp WHERE id=?");
                    preparedStatement.setInt(1, id);
                    boolean b=preparedStatement.execute();
                    if(b==true)
                           System.out.println("1 record deleted...");
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           preparedStatement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void readEmployees() {
             Connection connection = null;
             Statement statement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
                                  PASSWORD);
                    statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery("SELECT * FROM emp");
                    ResultSetMetaData metaData = resultSet.getMetaData();
                    int noCols = metaData.getColumnCount();
                    for (int i = 1; i <= noCols; i++) {
                           if (i != 3)
                                  System.out.printf("%-10s\t", metaData.getColumnName(i).toUpperCase());
                    }
                    System.out.println();
                    while (resultSet.next()) {
                           for (int i = 1; i <= noCols; i++) {
                                  if (i != 3)
                                        System.out.printf("%-10s\t", resultSet.getObject(i));
                           }
                           System.out.println();
                    }
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           statement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void readEmployee(int id) {
             Connection connection = null;
             Statement statement = null;
             try {
                    Class.forName(JDBC_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
                                  PASSWORD);
                    statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery("SELECT * FROM emp WHERE id="+id);
                    ResultSetMetaData metaData = resultSet.getMetaData();
                    int noCols = metaData.getColumnCount();
                    for (int i = 1; i <= noCols; i++) {
                           if (i != 3)
                                  System.out.printf("%-10s\t", metaData.getColumnName(i).toUpperCase());
                    }
                    System.out.println();
                    while (resultSet.next()) {
                           for (int i = 1; i <= noCols; i++) {
                                  if (i != 3)
                                        System.out.printf("%-10s\t", resultSet.getObject(i));
                           }
                           System.out.println();
                    }
             } catch (SQLException sqlEx) {
                    sqlEx.printStackTrace();
                    System.exit(1);
             } catch (ClassNotFoundException clsNotFoundEx) {
                    clsNotFoundEx.printStackTrace();
                    System.exit(1);
             } finally {
                    try {
                           statement.close();
                           connection.close();
                    } catch (Exception e) {
                           System.exit(1);
                    }
             }
       }

       public static void main(String[] args) {
             //createTable();
             createEmployee(1234, "Larson", 123, 1200, "New Jersey");
             createEmployee(5678, "Jones", 123, 1100, "New Jersey");
             createEmployee(7890, "Kapil", 345, 1600, "Los Angeles");
             createEmployee(2341, "Myers", 123, 1800, "New Jersey");
             createEmployee(6784, "Bruce", 345, 2200, "Los Angeles");
             createEmployee(9636, "Neumann", 123, 3200, "New Jersey");
             updateSalary(1234, 1000);
             createEmployee(1111, "Lee", 123, 4400, "New Jersey");
             deleteEmployee(1111);
             readEmployees();
             readEmployee(6784);
       }
}

Conclusion

Once one gets an idea of the CRUD operations of JDBC programming and how to write them, it’s just a matter of practice to master the intricacies of database manipulation. The above example is very minimalistic and a lot of checking/cross checking during data manipulation has been overlooked to keep it simple. For example the code can have a search method, which would actually use the same CRUD techniques, a checking should be there to verify the existence of a record before updating a record etc. However, if one grasps the CRUD techniques described above in Java code, the rest is just a walk in the park.

时间: 2024-08-26 23:09:19

数据库 —— 使用JDBC操作数据库的相关文章

JDBC操作数据库的学习(2)

在上一篇博客<JDBC操作数据库的学习(1)>中通过对例1,我们已经学习了一个Java应用如何在程序中通过JDBC操作数据库的步骤流程,当然我们也说过这样的例子是无法在实际开发中使用的,本篇就在简单开发中如何对上一篇的例子进行“升级”,满足简单开发中对数据库的增删改查(CRUD). 如果按照上一篇中的例子,那么我们在做增删改查的话将会出现每个方法都要获取连接,释放资源,代码会出现很大的重复性,因此我们应该将每个增删改查每个方法中可以复用的代码抽取出来,同时为了能切换数据库方便,也该将一些配置信

jdbc操作数据库语句

非常有用的jdbc操作数据库语句,记录下来,以方便以后的查询. public class PersonDao { // 增加操作 public void insert(Person person) throws Exception; // 修改操作 public void update(Person person) throws Exception; // 删除操作 public void delete(String id) throws Exception ; // 按ID查询操作 publi

JDBC操作数据库的学习(1)

单单对数据库的操作,比如说MySQL,我们可以在命令行窗口中执行,但是一般是应用程序要操作数据库,因此我们应该在程序中的代码上体现对数据库的操作,那么使用程序应用如何操作数据库呢?那就要使用到数据库的连接驱动,应用程序通过这些驱动来操作数据库: 但是这里就又有一个问题了,不同的数据库有各自的驱动程序,而一个应用程序要操作不同的数据库,那么就要懂得要使用的数据库的驱动如何操作,这样就增加了学习成本.好在我们使用Java开发应用,而Java中只需要使用JDBC就能操作所有的数据库,因为JDBC提供的

几种通过JDBC操作数据库的方法,以及返回数据的处理

1.SQL TO String :只返回一个查询结果 例如查询某条记录的总数 rs = stmt.executeQuery(replacedCommand);             if (rs != null && rs.next()) // rs only contains one row and one column             {                    String tempStr = rs.getString(1);                 

JDBC操作数据库的基本步骤

JDBC操作数据库的基本步骤: 1)加载(注册)数据库驱动(到JVM). 2)建立(获取)数据库连接. 3)创建(获取)数据库操作对象. 4)定义操作的SQL语句. 5)执行数据库操作. 6)获取并操作结果集. 7)关闭对象,回收数据库资源(关闭结果集-->关闭数据库操作对象-->关闭连接). package com.yangshengjie.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java

Spark Streaming通过JDBC操作数据库

本文记录了学习使用Spark Streaming通过JDBC操作数据库的过程,源数据从Kafka中读取. Kafka从0.10版本提供了一种新的消费者API,和0.8不同,因此Spark Streaming也提供了两种API与之对应,其中spark-streaming-kafka-0-8支持Kafka 0.8.2.1以后的Broker:spark-streaming-kafka-0-10支持0.10.0以上Broker,处于实验阶段.两者的对比如下表所示. |spark-streaming-ka

JDBC操作数据库的基本操作

JDBC操作数据库的基本步骤: 1)加载(注册)数据库驱动(到JVM). 2)建立(获取)数据库连接. 3)创建(获取)数据库操作对象. 4)定义操作的SQL语句. 5)执行数据库操作. 6)获取并操作结果集. 7)关闭对象,回收数据库资源(关闭结果集-->关闭数据库操作对象-->关闭连接). 1 package com.yangshengjie.jdbc; 2 import java.sql.Connection; 3 import java.sql.DriverManager; 4 imp

JDBC操作数据库的三种方式比较

JDBC(java Database Connectivity)java数据库连接,是一种用于执行上sql语句的javaAPI,可以为多种关系型数据库提供统一访问接口.我们项目中经常用到的MySQL.oracle.DB2等关系型数据库均是通过JDBC来访问的,现在主流的ORM框架Hibernate.Mybatis等均是在JDBC的基础上做的进一步封装.优化.一般小型的项目,可以直接用JDBC来访问数据库,简单方便.我在进过几个项目后,总结了三总JDBC的基本用法,对这几种用法做一个总结. 第一种

JDBC操作数据库的详细步骤

JDBC操作数据库的步骤: 1.注册驱动 告知JVM使用的是哪一个数据库的驱动 2.获得连接 使用JDBC中的类,完成对MySQL数据库的连接 3.获得语句执行平台 通过连接对象获取对SQL语句的执行者对象 4.执行sql语句 使用执行者对象,向数据库执行SQL语句 获取到数据库的执行后的结果 5.处理结果 6.释放资源  一堆close() 1.注册驱动,发射技术,将驱动加入到内容 使用java.sql.DriverManager类静态方法 registerDriver(Driver driv