封装类
package JDBChelp;
import java.sql.*;
//jdbc封装类
public class JDBChelp {
private JDBChelp(){}
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception{
String url="jdbc:mysql://localhost:3306/mydate";
String user="root";
String password ="123456";
return DriverManager.getConnection(url,user,password);
}
public static void close(Connection con , Statement sta, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(sta!=null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试
package JDBCpackage;
import JDBChelp.JDBChelp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//测试JDBChelp封装类
//测试模糊查询
public class JDBCtest05 {
public static void main(String[] args) {
Connection con=null;
PreparedStatement ps=null;
ResultSet set=null;
try {
con= JDBChelp.getConnection();//链接
String sql ="select name from student where name like ?";
ps=con.prepareStatement(sql);
ps.setString(1,"张三");
set=ps.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBChelp.close(con,ps,set);
}
}
}
这也是链接数据库的一种方法,把代码封装可以简短后面的代码!但不是必要的!
|