jdbc的模板
以下作为自己的在线模板使用,只是平时练习中的一段代码
public String selectProvinceName(Integer proid) {
String reName = "";
String URL = "jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf8";
String USER = "root";
String PASSWORD = "root";
ResultSet rs = null;
PreparedStatement pst = null;
Connection conn = null;
//1.加载驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
//2.获得数据库链接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
String sql = "select name from province where id = ?";
pst = conn.prepareStatement(sql);
pst.setInt(1, proid);
//4.处理数据库的返回结果(使用ResultSet类)
rs = pst.executeQuery();
if (rs.next()) {
reName = rs.getString("name");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
try {
//关闭资源
rs.close();
pst.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return reName;
}
public Province selectProvinceById(Integer proid) {
String URL = "jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf8";
String USER = "root";
String PASSWORD = "root";
ResultSet rs = null;
PreparedStatement pst = null;
Connection conn = null;
Province pro = null;
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
String sql = "select id,name,jiancheng,shenghui from province where id = ?";
pst = conn.prepareStatement(sql);
pst.setInt(1, proid);
//4.处理数据库的返回结果(使用ResultSet类)
rs = pst.executeQuery();
if (rs.next()) {
pro = new Province();
pro.setProid(rs.getInt(1));
pro.setProname(rs.getString(2));
pro.setProjiancheng(rs.getString(3));
pro.setProshenghui(rs.getString(4));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
//关闭资源
rs.close();
pst.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return pro;
}
@兄弟们加油,未来可期!!!

浙公网安备 33010602011771号