一.准备条件
外界条件
在数据库中首先创建表空间在创建的表中添加数据
代码部分
导入数据库的驱动包(jar)加载数据库驱动获取数据库连接编写sql语句利用prepareStatement进行预处理设置参数,参数1代表第几个参数(从1开始),参数2代表参数的值向数据库发出sql语句进行查询,executeQuery(),查询到结果集resultSet遍历结果集释放资源(connection,resultSet,prepareStatement)
PrepareStatement的好处
达到预处理的目的,提高效率(由于我们编写代码时,每编写一句就会进行编译,效率变低,如果使用了prepareStatement预处理,这样,如果我们编写到之前出现过的相同的sql语句,就可以不用进行编译了,这样效率就可以提高了)
源码public static void main(String[] args) {//声明链接Connection connection=null;//预处理PreparedStatement preparedStatement=null;//获取的结果集ResultSet resultSet=null;//加载驱动try {Class.forName("com.mysql.jdbc.Driver");//获取链接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");//创建sql语句String sql="select * from user where username= ? ";//预处理 preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, "王五");resultSet = preparedStatement.executeQuery();while(resultSet.next()){System.out.println(resultSet.getString("id")+resultSet.getString("username"));}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//释放资源if(resultSet!=null){try {resultSet.close();} catch (Exception e2) {// TODO: handle exception}}if(connection!=null){try {connection.close();} catch (Exception e2) {// TODO: handle exception}}if(preparedStatement!=null){try {preparedStatement.close();} catch (Exception e2) {// TODO: handle exception}}}}
转载于:https://www.cnblogs.com/itcx1213/p/6337637.html