您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

preparedStatement和statement

preparedStatement 可以防止SQL注入,做了预编译处理
而 statement不能

preparedStatement代码
public static void executeSQL(){
try {
String sql=“select * from users”;
//通过反射机制注册驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);
//获取mysql连接
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/ripe”, “root”, “123”);
//将要执行的SQL语句放入,得到预编译对象
PreparedStatement prepareStatement = connection.prepareStatement(sql);
//执行查询,获得结果
ResultSet resultSet = prepareStatement.executeQuery();
int i=1;
while (resultSet.next()){
//遍历结果,通过字段名得到对应的值
System.out.println(resultSet.getString(“account”));
System.out.println(i++);
}
resultSet.close();
prepareStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}

preparedStatement带参数的执行
public static void executeHaveParam(){
try {
String sql=“update users set account=? where age=?”;
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:mysql:///ripe”, “root”, “123”);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,“chenglong.fan”);
preparedStatement.setInt(2,12);
boolean execute = preparedStatement.execute();
if (execute){
System.out.println(“修改成功”);
}else {
System.out.println(“修改失败”);
}

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Statement 程序

public class JdbcStatement {
public void excuteSQL(){
try {
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:mysql:///ripe”, “root”, “123”);
Statement statement = connection.createStatement();
String sql=“select * from users”;
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println(resultSet.getString(“account”));
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
    new JdbcStatement().excuteSQL();
}

}


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进