数据库 —— 使用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
2.RDBMS Package (For example, MySQL, Oracle, PostgreSQL, etc.)
3.IDE (For example, Eclipse, NetBeans, JDeveloper, 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/J is 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.
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 Create, Read, Update 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.
版权声明 本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者 BensonLaur 和本文原始地址: https://www.cnblogs.com/BensonLaur/p/5426259.html |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端