java中的PreparedStatement类似于php中的pdo,只不过实现方式不同,但事实上都是通过预处理或者编译的方法对数据库进行增删改查,也只有这样才能有效的防止sql注入的发生。
增删改的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class TestConn {
private static final String DBURL="jdbc:mysql://localhost:3306/数据库名";
private static final String DBUSER="root";
private static final String DBPWD="数据库密码";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement pstmt = null;
try {
//a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.jdbc.Driver");//驱动类
//b.与数据库建立连接
connection = DriverManager.getConnection(DBURL,DBUSER,DBPWD);
//PreparedStatement
String sql = "insert into users values(?,?,?)";
pstmt = connection.prepareStatement(sql);//预编译
pstmt.setInt(1,36);
pstmt.setString(2,"adminadmin");
pstmt.setString(3,"password");
int count = pstmt.executeUpdate();
//d.处理结果
if(count > 0) {
System.out.println("操作成功");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
if(pstmt!=null) pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
查找的代码:
PreparedStatement是先声明sql,Statement是后声明sql,因此在查询的时候 pstmt.executeQuery();中就不需要传入sql语句了
package caishu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConn2 {
private static final String DBURL="jdbc:mysql://localhost:3306/数据库名";
private static final String DBUSER="root";
private static final String DBPWD="数据库密码";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection = null;
ResultSet rs=null;
PreparedStatement pstmt = null;
try {
//a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.jdbc.Driver");//驱动类
//b.与数据库建立连接
connection = DriverManager.getConnection(DBURL,DBUSER,DBPWD);
//PreparedStatement
String sql = "select * from users where id=?";
pstmt = connection.prepareStatement(sql);//预编译
pstmt.setInt(1,1);
rs = pstmt.executeQuery();//返回值表示增删改几条数据
//d.处理结果
while(rs.next()) {
int id = rs.getInt("id");//等价于int id = rs.getInt(1);
System.out.println(id);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
//先开的后关,后开的先关
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}