JDBC连接数据库
数据库是用于管理数据的,后台是用于根据业务做逻辑处理的,前台显示数据并进行交互
步骤:
1、关联数据库驱动包(不同的数据库使用的驱动包是不一样的)
2、注册驱动(通过反射进行驱动的注册)
3、连接数据库获取数据库连接对象(登录-选择数据库的过程)
4、执行SQL语句
5、处理结果集
6、关闭数据库连接对象
首先需要关联数据驱动包 jar包 跟数据库要匹配
public static void look() {
Connection conne =null;
Statement state =null;
ResultSet resu =null;
try {
//1、注册驱动
Class.forName(DRIVER);
//2、连接数据库
conne = DriverManager.getConnection(URL,USER,PAAWORD);
//3、定义SQL
String SQL = "select * from score";
//4、执行SQL 需要 Statement对象
state = conne.createStatement();
//5、执行SQL 获取结果处理结果集
resu = state.executeQuery(SQL);
//遍历结果集
while(resu.next()) {
int s = resu.getInt("s_id");
int c = resu.getInt("c_id");
int sc =resu.getInt("s_score");
System.out.println(s+"-----"+c+"-----"+sc);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭
try {
if(resu!=null) {
resu.close();
}
if(state!=null) {
state.close();
}
if(conne!=null) {
state.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC的封装
//注册驱动 每次使用都要注册驱动 所以可以定义为静态代码块
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("注册驱动失败");
e.printStackTrace();
}
}
//登入方法 返回Connection对象,连接数据库
public static Connection newInstance() throws SQLException {
if (conne==null) {
conne = DriverManager.getConnection(URL,USER,PAAWORD);
}
return conne;
}
// 综合方法:传入 String 要执行的增删改
public static int tool(String sql) {
try {
//执行SQL需要statement对象
state = newInstance().createStatement();
//执行sql语句,
int rest = state.executeUpdate(sql);
return rest;
}catch (SQLException e) {
e.printStackTrace();
}finally {
if(state!=null) {
try {
if(state!=null) {
state.close();
}
if(conne!=null) {
conne.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return 0;
}
封装可以简化代码, 方便使用