import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class QueryDemo {
public static void main(String[] args) throws Exception {
QueryDemo demo = new QueryDemo();
demo.findAllDept();
}
//查找所有的部门
public void findAllDept() throws ClassNotFoundException, SQLException{
//1.注册数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.与数据库建立连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://@localhost:3306/oaec",
"root", "root");
//3.创建用来执行SQL语句的Statement对象
Statement stmt = conn.createStatement();
//4.执行SQL语句
String sql = "select id,name,region_id from s_dept";
//执行查询:executeQuery(String sql)==>ResultSet,结果集
//增删改:executeUpdate(String sql)==>int,影响的行数
ResultSet rs = stmt.executeQuery(sql);
//5.处理结果集(针对查询)
while(rs.next()) {
//一次循环处理一行
int id = rs.getInt(1);
String name = rs.getString(2);
int regionId = rs.getInt(3);
//展示简单输出
System.out.println(id+","+name+","+regionId);
}
//6.释放资源
//ResultSet-->Statement-->Connection
if(rs!=null) {
rs.close();
}
if(stmt!=null) {
stmt.close();
}
if(conn!=null) {
conn.close();
}
}
}
JDBC需要加到项目的外库中,否则不能连接.