使用原始的 JDBC 操作数据库
jdbc 使用步骤:
// 1、注册driver
Class.forName("com.mysql.jdbc.Driver");
// 2、建立数据库连接对象
Connection conn = DriverManager.getConnection(url_encrypt, user, password);
// 3、建立操作对象
Statement stmt= conn.createStatement();
// 4、结果集
ResultSet rs = stmt.executeQuery("select * from information");
// 5、依次关闭结果集,操作对象,数据库对象
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
可以看出,使用jdbc的步骤简单归纳如下:
- 加载数据库驱动
driver
- 建立数据库连接
Connection
- 创建
Statement
- 通过
statement
执行sql
,获得结果集ResultSet
- 依次关闭
ResultSet
,Statement
,Connection
特别注意:连接数据库,需要添加对应数据库的驱动包。可参考文章:数据库驱动包
常见报错:java.sql.SQLException: 不支持的字符集 (在类路径中添加 orai18n.jar): ZHS16GBK
附录:使用原始的 JDBC 操作数据库的完整案例
1、连接 MySQL 数据库
package com.example.jdbctemplateproject.utils; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * 数据源连接工具 * * @author: shipleyleo * @create: 2023-04-07 17:32:16 */ public class DataSourceConnectionUtils { public static void jdbcTest(String url, String username, String password) throws ClassNotFoundException, SQLException { // 1、注册driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2、建立数据库连接对象 Connection conn = DriverManager.getConnection(url, username, password); // 3、建立操作对象 Statement stmt = conn.createStatement(); // 4、结果集 ResultSet rs = stmt.executeQuery("select * from student"); while(rs.next()) { // 转换每行的返回值到 Map 中 System.out.println("id:" + rs.getLong("id") + ",name:" + rs.getString("name")); } // 5、依次关闭结果集,操作对象,数据库对象 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } public static void main(String[] args) { try { jdbcTest("jdbc:mysql://localhost:3306/jdbc_test", "root", "******"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
2、连接 Oracle 数据库
package com.example.jdbctemplateproject.utils; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * 数据源连接工具 * * @author: shipleyleo * @create: 2023-04-07 17:32:16 */ public class DataSourceConnectionUtils { public static void jdbcTest(String url, String username, String password) throws ClassNotFoundException, SQLException { // 1、注册driver Class.forName("oracle.jdbc.driver.OracleDriver"); // 2、建立数据库连接对象 Connection conn = DriverManager.getConnection(url, username, password); // 3、建立操作对象 Statement stmt = conn.createStatement(); // 4、结果集 ResultSet rs = stmt.executeQuery("select * from student"); while(rs.next()) { // 转换每行的返回值到 Map 中 System.out.println("id:" + rs.getLong("id") + ",name:" + rs.getString("name")); } // 5、依次关闭结果集,操作对象,数据库对象 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } public static void main(String[] args) { try { jdbcTest("jdbc:oracle:thin:@localhost:1521:orcl", "system", "******"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
从上面的两个完整例子可以看出,MySQL 和 Oracle 数据源连接工具的主要差别:
数据库驱动
不同、URL
不同。如下图所示。
参考资料
相关文章