jdbc-实现简单的增删改查

jdbc-实现简单的增删改查

前情提要
jdbc
1.加载驱动
2.创建链接
3.写sql
4.得到statement对象
5.执行sql得到结果集
6.处理结果集
7.关闭资源

使用jdbc实现一个简单的增删改查

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Add {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection=DBUtil.getConnection();
        System.out.println("创建连接成功");
        String sql="insert into tb_user (username,password) value ('231','342')";
        PreparedStatement statement=connection.prepareStatement(sql);
        statement.executeUpdate();
        System.out.println("增加成功");
        DBUtil.closeAll(null,statement,connection);
    }
}

public class Delete {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection=DBUtil.getConnection();
        System.out.println("创建连接成功");
        String sql="delete from tb_user where id=2";
        PreparedStatement statement=connection.prepareStatement(sql);
        statement.executeUpdate();
        System.out.println("删除成功");
        DBUtil.closeAll(null,statement,connection);
    }
}

public class Change {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection=DBUtil.getConnection();
        System.out.println("创建连接成功");
        String sql="update tb_user set password='66666' where username='eee'";
        PreparedStatement statement=connection.prepareStatement(sql);
        statement.executeUpdate();
        System.out.println("更改成功");
        DBUtil.closeAll(null,statement,connection);
    }
}

public class Find {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection=DBUtil.getConnection();
        String sql="select * from tb_user";
        PreparedStatement statement=connection.prepareStatement(sql);
        ResultSet resultSet=statement.executeQuery();

        while (resultSet.next()){
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
            System.out.println(resultSet.getString(3));
        }
        System.out.println("查询成功");
        DBUtil.closeAll(resultSet,statement,connection);
    }
}

连接数据库

public class DBUtil {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","123456");
        return connection;
    }
    public static void closeAll(ResultSet resultSet, Statement statement,Connection connection) throws SQLException {
        if (resultSet!=null){
            resultSet.close();
        }
        if (statement!=null){
            statement.close();
        }
        if (connection!=null){
            connection.close();
        }
    }
}

你可能感兴趣的:(jdbc-实现简单的增删改查)