一.配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.xx.xxx:3306/workSQL
user=root
pwd=ok
二.连接、查询、更改
public class PstDao {
private static String driver= Prop.getP("driver");
private static String url=Prop.getP("url");
private static String user=Prop.getP("user");
private static String pwd=Prop.getP("pwd");
public static Connection getConn(){
try {
Class.forName(driver);
return DriverManager.getConnection(url,user,pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn, PreparedStatement pst, ResultSet res){
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static ResultSet query(String sql,Object ...params){
Connection conn = getConn();
PreparedStatement pst=null;
ResultSet rst=null;
try {
pst = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1,params[i]);
}
rst = pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rst;
}
public static int update(String sql,Object... params){
Connection conn = getConn();
PreparedStatement pst=null;
try {
pst =conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1,params[i]);
}
return pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}}
三.测试部分
public class PstDaoTest {
@Test
public void query() throws SQLException {
String sql="select * from grade where grade_cj> ?;";
ResultSet rst = PstDao.query(sql,90);
while (rst.next()) {
System.out.println(rst.getInt("grade_stuid")+"---"+rst.getInt("course_id")+"---"+rst.getInt("grade_cj"));
}
}
@Test
public void update() throws SQLException {
String sql="update grade set grade_cj=100 where grade_stuid=?;";
int i=PstDao.update(sql,2);
System.out.println(i);
}
}
}