TbUserDao增删查改
public class TbUserDao {
static Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
static {
try {
connection = DBUtil.getConnection(DBUtil.qudong,DBUtil.url);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
TbUserDao text = new TbUserDao();
List<TbUser> users = text.findAll();
System.out.println(users);
TbUserDao dele = new TbUserDao();
dele.delete(1);
TbUserDao add = new TbUserDao();
add.add("insert into test01 values (6, 'Bill', 'Xuanwumen')");
TbUserDao update = new TbUserDao();
update.update("update test01 set name='adsf' where id=3");
}
public void delete(int id) {
try {
String sql = "delete from test01 where id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.Closeall(null,preparedStatement,connection);
}
}
public void add(String sql) {
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.execute();
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.Closeall(null,preparedStatement,connection);
}
}
public void update(String sql) {
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.execute();
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.Closeall(null,preparedStatement,connection);
}
}
public List<TbUser> findAll(){
List <TbUser> users = new ArrayList<>();
try {
String sql = "select * from test01";
preparedStatement = connection.prepareStatement(sql);
resultSet=preparedStatement.executeQuery();
while (resultSet.next()){
TbUser user = new TbUser();
user.setId(resultSet.getInt(1));
user.setName(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
users.add(user);
System.out.println("查询成功");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.Closeall(resultSet,preparedStatement,connection);
}
return users;
}
数据库连接 与 释放资源 DBUtil
public class DBUtil {
public final static String qudong="com.mysql.jdbc.Driver";
public final static String url="jdbc:mysql://localhost:3306/ssmpeixun?user=root&password=";
public static Connection getConnection(String qudong, String url) throws Exception{
Class.forName(qudong);
Connection connection = DriverManager.getConnection(url);
System.out.println("数据库连接成功");
return connection;
}
public static void Closeall(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection){
try {
if (resultSet!=null) {
resultSet.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (preparedStatement!=null) {
preparedStatement.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("成功关闭");
}
}