获取数据库连接信息
- String dbDriver="com.mysql.cj.jdbc.Driver";
- String dbUser="root";
- String dbPassword="iytb890214";
- String dbUrl="jdbc:mysql://localhost:3306/db_jdbc_demo?serverTimezone=GMT%2B8&characterEncoding=utf8&useSSL=true";
导入数据库连接Jar包
- mysql-connector-java-6.0.6.jar
1. 装载相应的数据库的JDBC驱动并进行初始化
// 加载数据库驱动 Class.forName(dbDriver);
2. 建立JDBC和数据库之间的Connection连接
//获取连接 Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
3. 创建Statement或者PreparedStatement接口,执行SQL语句
3.1 创建Statement
//创建Statement Statement statement = conn.createStatement(); String strSQL = "select * from t_student"; //创建ResultSet ResultSet rs = statement.executeQuery(strSQL);
3.2 创建PreparedStatement
String strSQL = "select * from t_student where stuId=? and stuName like ?"; PreparedStatement pst = conn.prepareStatement(strSQL); pst.setString(1, "b4c93f98-e104-4a78-86ad-11f6292692c4"); pst.setString(2, "%李%"); ResultSet rs = pst.executeQuery();
4. 处理和显示结果
while (rs.next()) { Student student = new Student(); student.setStuId(rs.getString("stuId")); student.setStuName(rs.getString("stuName")); System.out.println(student); }
5. 释放资源
/** * 关闭连接Connection * * @param conn */ public static void closeConnection(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException ex) { LogUtil.getInstance().error(ex.getMessage()); } } } /** * 关闭Statement * * @param st */ public static void closeStatement(Statement st) { if (st != null) { try { st.close(); } catch (SQLException ex) { LogUtil.getInstance().error(ex.getMessage()); } } } /** * 关闭PreparedStatement * * @param pst */ public static void closePreparedStatement(PreparedStatement pst) { if (pst != null) { try { pst.close(); } catch (SQLException ex) { LogUtil.getInstance().error(ex.getMessage()); } } } /** * 关闭存储过程 * * @param cs */ public static void closeCallableStatement(CallableStatement cs) { if (cs != null) { try { cs.close(); } catch (SQLException ex) { LogUtil.getInstance().error(ex.getMessage()); } } } /** * 关闭ResultSet * * @param rs */ public static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException ex) { LogUtil.getInstance().error(ex.getMessage()); } } }