避免Sql注入的问题。 不用Statement 而用PrepareStatement
预编译 然后手工赋值 setInt or setString
插入:
public class TestInsert {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
try {
conn = JdbcUtils.getConnection();
//区别 使用? 占位符代替参数
String sql = "insert into account(id,`name`,`money`) VALUES(?,?,?)";
st = conn.prepareStatement(sql); //预编译sql,先写sql,然后不执行
//手工给参数赋值
st.setInt(1,3);
st.setString(2,"CCCCC");
st.setDouble(3,60000.00);
//执行
int i = st.executeUpdate();
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,null);
}
}
}
查询
public class TestSelect {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//区别 使用? 占位符代替参数
String sql = "select * from account where `id`=? or `id`=?";
st = conn.prepareStatement(sql); //预编译sql,先写sql,然后不执行
//手工给参数赋值
st.setInt(1,1);
st.setInt(2,2);
rs = st.executeQuery();
while (rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,null);
}
}
}
标签:25,JDBC,String,2023,st,JdbcUtils,sql,null,conn From: https://www.cnblogs.com/RUI2022/p/17154020.html