在进行jdbc程序编写的时候,因为对数据库操作很多,
如果访问数据库很频繁,Connection不要设置成static
当编辑jdbc.properties文件时,window最后一栏preference里面找到
防止SQL注入:
package com.sql; import java.sql.*; public class Demo2 { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null;// 预处理对象 ResultSet rs = null; try { // 1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); System.out.println("建立连接成功"); // 2.建立连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hello", "root", "123456"); conn.setAutoCommit(false); System.out.println(conn); // 3.创建ps,代表预编译对象 ps = conn.prepareStatement("select* from student where id=? and name=?"); // ps可以给?赋值 ps.setInt(1, 6); ps.setString(2, "王志"); // 4.执行 rs = ps.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); // 如果sql语句中任何语句出错,可以整体回滚 try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { if (conn != null) { try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } conn = null; } if (rs != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception } rs = null; } if (ps != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } ps = null; } } } }
sqlHelper:
package com.sql; import java.io.FileInputStream; import java.io.IOException; import java.sql.*; import java.util.Properties; import javax.management.RuntimeErrorException; public class sqlHelper { // 定义需要的变量 private static Connection ct = null; private static Statement sm = null; private PreparedStatement ps = null; private static ResultSet rs = null; // 连接数据库的参数 private static String url = ""; private static String user = ""; private static String driver = ""; private static String password = ""; private static Properties pp = null; private static FileInputStream fis = null; // 加载一次驱动 static { try { // 读取配置信息 pp = new Properties(); fis = new FileInputStream("dbinfo.properties"); pp.load(fis); url = pp.getProperty("url"); driver = pp.getProperty("driver"); password = pp.getProperty("password"); user = pp.getProperty("user"); Class.forName(url); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fis = null; } } // 得到连接 public static Connection getConnection() { try { ct = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return ct; } // 自动获取 // 先写一个修改update/insert/delete语句 // sql格式:update 表名字 set 字段名=? where 字段=? // parameters 应该是("abc",23); public void excuteUpdate(String sql, String[] parameters) { // 创建一个ps try { ct = getConnection(); ps = ct.prepareStatement(sql); // 给?赋值 if (parameters != null) { for (int i = 0; i < parameters.length; i++) { ps.setString(i + 1, parameters[i]); } } // 执行 ps.executeUpdate(); } catch (Exception e) { e.printStackTrace();// 开发阶段 // 抛出异常,抛出运行异常可以给调用该函数的函数一个选择,可以处理也可以放弃处理 throw new RuntimeException(e.getMessage()); // TODO: handle exception } finally { close(rs, ps, ct); } } // 如果有多个则要考虑事务 public static void excuteUpdate2(String sql[], String[][] parameters) { } public static void close(ResultSet rs, Statement ps, Connection conn) { if (conn != null) { try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } conn = null; } if (rs != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception } rs = null; } if (ps != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } ps = null; } } }
dbinfo.properties
#这是我的mysql配置 url=jdbc:mysql://localhost:3306/hello user=root driver=com.mysql.jdbc.Driver password=123456
完成版:
sqlHelper:
package com.sql; import java.io.FileInputStream; import java.io.IOException; import java.sql.*; import java.util.Properties; import javax.management.RuntimeErrorException; public class sqlHelper { // 定义需要的变量 private static Connection ct = null; private static Statement sm = null; private static PreparedStatement ps = null; private static ResultSet rs = null; private static CallableStatement cs = null; // 连接数据库的参数 private static String url = ""; private static String user = ""; private static String driver = ""; private static String password = ""; private static Properties pp = null; private static FileInputStream fis = null; // 加载一次驱动 static { try { // 读取配置信息 pp = new Properties(); fis = new FileInputStream("dbinfo.properties"); pp.load(fis); url = pp.getProperty("url"); driver = pp.getProperty("driver"); password = pp.getProperty("password"); user = pp.getProperty("user"); Class.forName(driver); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fis = null; } } // 得到连接 public static Connection getConnection() { try { ct = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return ct; } // 自动获取 // 先写一个修改update/insert/delete语句 // sql格式:update 表名字 set 字段名=? where 字段=? // parameters 应该是("abc",23); public static void excuteUpdate(String sql, String[] parameters) { // 创建一个ps try { ct = getConnection(); ps = ct.prepareStatement(sql); // 给?赋值 if (parameters != null) { for (int i = 0; i < parameters.length; i++) { ps.setString(i + 1, parameters[i]); } } // 执行 ps.executeUpdate(); } catch (Exception e) { e.printStackTrace();// 开发阶段 // 抛出异常,抛出运行异常可以给调用该函数的函数一个选择,可以处理也可以放弃处理 throw new RuntimeException(e.getMessage()); // TODO: handle exception } finally { close(rs, ps, ct); } } // 分页问题 public static ResultSet executeQuery2() { return rs; } // 调用存储过程,有返回值 // 调用存储过程(无返回值) public static void callProl(String sql, String[] parameters) { try { ct = getConnection(); cs = ct.prepareCall(sql); // 给?赋值 if (parameters != null) { for (int i = 0; i < parameters.length; i++) { cs.setObject(i + 1, parameters[i]); } } cs.execute(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } finally { close(rs, cs, ct); } } // 统一的select public static ResultSet executeQuery(String sql, String[] parameters) { try { ct = getConnection(); ps = ct.prepareStatement(sql); if (parameters != null && !parameters.equals("")) {// 健壮 for (int i = 0; i < parameters.length; i++) { ps.setString(i + 1, parameters[i]); } } rs = ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } return rs; } // step2 public static void excuteUpdate2(String sql[], String[][] parameters) { try { // 1.获得连接 ct = getConnection(); // 因为这时用户传入的可能多个sql语句 ct.setAutoCommit(false); for (int i = 0; i < sql.length; i++) { if (parameters[i] != null) { ps = ct.prepareStatement(sql[i]); for (int j = 0; j < parameters[i].length; j++) { ps.setString(j + 1, parameters[i][j]); } ps.executeUpdate(); } } // int i=9/0; ct.commit(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); // 回滚 try { ct.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { close(rs, ps, ct); } } public static void close(ResultSet rs, Statement ps, Connection conn) { if (conn != null) { try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } conn = null; } if (rs != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception } rs = null; } if (ps != null) { try { ps.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } ps = null; } } // 自动获取 public static Connection getCt() { return ct; } public static void setCt(Connection ct) { sqlHelper.ct = ct; } public static Statement getSm() { return sm; } public static void setSm(Statement sm) { sqlHelper.sm = sm; } public static PreparedStatement getPs() { return ps; } public static void setPs(PreparedStatement ps) { sqlHelper.ps = ps; } public static ResultSet getRs() { return rs; } public static void setRs(ResultSet rs) { sqlHelper.rs = rs; } public static String getUrl() { return url; } public static void setUrl(String url) { sqlHelper.url = url; } public static String getUser() { return user; } public static void setUser(String user) { sqlHelper.user = user; } public static String getDriver() { return driver; } public static void setDriver(String driver) { sqlHelper.driver = driver; } public static String getPassword() { return password; } public static void setPassword(String password) { sqlHelper.password = password; } public static Properties getPp() { return pp; } public static void setPp(Properties pp) { sqlHelper.pp = pp; } public static FileInputStream getFis() { return fis; } public static void setFis(FileInputStream fis) { sqlHelper.fis = fis; } }
Testjdbc:实现增删改查功能
package com.sql; import org.junit.Test; import java.sql.*; public class Testjcbc { // 测试sqlHelper工具是否可以正常使用 @Test public void test() { // System.out.println("helloworld!"); // String sql="insert into student values(?,?,?,?,?)"; // String parameters[]={"8","张无忌","96","94","93"}; // sqlHelper.excuteUpdate(sql, parameters); } // 测试sqlHelper的考虑事务的 @Test public void testHelper2() { // String sql1 = "update student set Chinese=Chinese-20 where name=?"; String sql2 = "update student set Chinese=Chinese+10 where name=?"; String sqls[] = { sql1, sql2 }; String sql1_paras[] = { "李进" }; String sql2_paras[] = { "王志" }; String[][] parameters = { sql1_paras, sql2_paras };// 二维数组装载 sqlHelper.excuteUpdate2(sqls, parameters); } @Test public void testHelper3() { String sql = "select *from student"; String parameters[] = { sql }; try { ResultSet rs = sqlHelper.executeQuery(sql, null); System.out.println(rs); while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { System.out.println(sqlHelper.getRs()); sqlHelper.close(sqlHelper.getRs(), sqlHelper.getPs(), sqlHelper.getCt()); } } @Test public void testHelper4() { try { String sql = "call pro(?,?)"; String parameters[] = { "17", "孙悟空" }; sqlHelper.callProl(sql, parameters); } catch (Exception e) { e.printStackTrace(); } } } // https://www.cnblogs.com/mcad/p/4213632.html