jdbc练习demo
//连接云端服务器数据库工具类 public class TestJDBCUtil { public static String driver="com.mysql.jdbc.Driver"; public static String url = "jdbc:mysql://42.123.87.49:3306/aaaaa?useUnicode=true&characterEncoding=utf-8"; public static String user = "***"; public static String password = "****"; //获取1条数据库的连接 private static Connection getConnection() { Connection con = null; //返回的连接 try { //1 加载驱动 Class.forName(driver); con = DriverManager.getConnection(url, user, password); //2 获取连接 } catch (Exception e) { e.printStackTrace(); } return con; } //查询:简单查询,不含?的sql语句 public static ResultSet doQuery(String sql) { return doQuery(sql,null); } //查询:复杂查询,含有多个?的sql语句 public static ResultSet doQuery(String sql,String... ps) { //1 获取连接 Connection con = getConnection(); //调用上面的方法,获取1个连接 if(con==null) { System.out.println("获取连接失败!"); return null; //提前终止本方法代码 } ResultSet rs = null; try { //2执行查询 PreparedStatement psm = con.prepareStatement(sql); //通过for循环,访问参数数组,给psm逐个设置可变参数!! if(ps!=null) //只有可变参数不为空,才进行?赋值 { for(int i=0;i<ps.length;i++) { psm.setString(i+1, ps[i]);//将第i个可变参数,设置到第i+1个问号 } } rs = psm.executeQuery(); } catch (Exception e) { e.printStackTrace(); } //3 返回结果 return rs; } //关闭资源。 public static void close(ResultSet rs) { Statement sm = null; Connection con = null; try { if (rs != null) { sm = rs.getStatement(); rs.close(); } if (sm != null) { con = sm.getConnection(); sm.close(); } if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String sql="SELECT * FROM cj_scenedatadetail"; ResultSet rs =TestJDBCUtil.doQuery(sql); int i=0; //System.out.println(rs+"***"); try { while (rs.next()) { String retainedCount = rs.getString("content_varchar"); System.out.println(" 留存信息:"+retainedCount); i++; } System.out.println("留存总数量:"+(i-1)); } catch (Exception e) { e.printStackTrace(); } } }