一、建立数据库连接
在使用MySQLConnection进行操作前,首先需要建立数据库连接,代码示例如下:
try { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); }
上述代码中,我们通过jdbc:mysql://localhost:3306/test建立了一个到本地test数据库的连接,用户名和密码分别为root和root。
此外,我们还需要捕获可能出现的SQLException异常。
二、执行SQL语句
建立好数据库连接后,我们就可以通过MySQLConnection向数据库执行SQL语句了,代码示例如下:
Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); String sql = "SELECT * FROM student WHERE age > 18"; rs = stmt.executeQuery(sql); while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("Name: " + name + " age: " + age); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
上述代码中,我们首先通过conn.createStatement()创建一个Statement对象,然后使用stmt.executeQuery(sql)方法执行查询操作,将结果保存在ResultSet对象中。最后,通过rs.next()逐行遍历结果集,获取每一行的数据。
此外,我们还需要在finally块中关闭ResultSet、Statement和Connection对象,可以避免连接泄漏。
三、预处理SQL语句
在执行SQL语句时,如果SQL语句包含变量,需要通过预处理机制进行处理。代码示例如下:
PreparedStatement pstmt = null; try { String sql = "INSERT INTO student (name, age) VALUES (?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Tom"); pstmt.setInt(2, 20); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
上述代码中,我们首先使用conn.prepareStatement(sql)创建一个PreparedStatement对象,然后通过pstmt.setString(1, “Tom”)和pstmt.setInt(2, 20)设置SQL语句中的变量值,最后通过pstmt.executeUpdate()执行SQL语句。
与执行普通SQL语句类似,我们还需要在finally块中关闭PreparedStatement和Connection对象。
四、事务处理
MySQLConnection还支持事务处理机制,可以通过开启事务来操作数据库。代码示例如下:
try { conn.setAutoCommit(false); // 关闭自动提交 Statement stmt = conn.createStatement(); String sql1 = "UPDATE student SET age = age - 1 WHERE name = 'Tom'"; stmt.executeUpdate(sql1); String sql2 = "UPDATE student SET age = age + 1 WHERE name = 'Jerry'"; stmt.executeUpdate(sql2); conn.commit(); // 提交事务 } catch (SQLException e) { try { conn.rollback(); // 回滚事务 } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { conn.setAutoCommit(true); // 恢复自动提交 conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
上述代码中,我们首先通过conn.setAutoCommit(false)关闭自动提交机制,然后将多个SQL语句放在同一个事务中执行,最后通过conn.commit()提交事务。如果事务执行失败,可以通过conn.rollback()回滚事务。最后,我们需要在finally块中恢复自动提交机制并关闭Connection对象。
原创文章,作者:FPYH,如若转载,请注明出处:https://www.506064.com/n/145062.html