基础的JDBC查询数据代码
@Test public void test2(){ Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test"; String passWord = "123456"; String username = "root"; //通过url和数据库用户名密码获取连接 connection = DriverManager.getConnection(url, username, passWord); //设置sql语句 String sql = "select * from `user` where id < ?"; //获取preparedStatement preparedStatement = connection.prepareStatement(sql); //设置预处理的值 preparedStatement.setInt(1,3); //执行查询 返回结果集 resultSet = preparedStatement.executeQuery(); ResultSetmetaData metaData = resultSet.getmetaData(); if (resultSet.next()){ for (int i = 1; i <=metaData.getColumnCount(); i++) { //获取列名和列值 注意下标要从1开始 System.out.print(metaData.getColumnName(i)+" "); System.out.println(resultSet.getObject(i)); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //关闭连接 try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
输出
id 1 username zhangsan password 123 name 张三
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)