我们可以建一个数据库工具类
public class DBUtils {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/navi?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "mysql123";
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
//释放资源
public static void release(PreparedStatement pstmt,Connection conn){
if(pstmt!=null){
try {
pstmt.close();
}catch (SQLException e){
e.printStackTrace();
}
pstmt = null;
}
if(conn!=null){
try {
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
conn = null;
}
}
public static void release(ResultSet rs,PreparedStatement pstmt, Connection conn){
if(rs!=null){
try {
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
rs = null;
}
release(pstmt,conn);
}
}
以下是一个例子说明如何运用上面的类
分别建立user类,userdao的接口以及实现接口的类
public class User {
private Integer id;
private String username;
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
public interface IUserDao {
public boolean insert(User user) throws SQLException;
public User find(int id);
}
public class UserDao implements IUserDao {
@Override
public boolean insert(User user) throws SQLException {
boolean ret = false;
Connection conn = null;
PreparedStatement pstmt= null;
try{
conn = DBUtils.getConnection();
String sql = "INSERT INTO user(id,username,password)"+"VALUES(?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,user.getId());
pstmt.setString(2,user.getUsername());
pstmt.setString(3,user.getPassword());
int result = pstmt.executeUpdate();
if(result>0){
ret = true;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
DBUtils.release(pstmt,conn);
}
return ret;
}
@Override
public User find(int id) {
return null;
}
}
最用创建一个测试类,测试我们能否实现数据库的交互
public class cs {
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, SQLException {
UserDao dao = new UserDao();
User user = new User(1,"ame","rotk");
boolean ret =dao.insert(user);
System.out.println(ret);
}
}
结果值为true,成功insert