数据库——jdbc编程
JDBC编程六步:
import java.sql.*;
import java.util.ResourceBundle;
public class JDBC_Test {
public static void main(String[] args) {
//使用资源绑定器绑定属性配置文件
ResourceBundle boundle= ResourceBundle.getBundle("jdbc");
String driver=boundle.getString("driver");
String url=boundle.getString("url");
String user=boundle.getString("user");
String password=boundle.getString("password");
Connection cnn=null;
Statement stmt=null;
ResultSet res=null;
try {
//第一步:注册驱动(这种方式是比较常用的)
//以下方法是不需要接收返回值的,因为我们只是想要它的类加载动作(类加载的时候执行类的静态代码块)
Class.forName(driver);
//第二步:获取连接
//url包括协议、IP、port、资源名
cnn= DriverManager.getConnection(url,user,password);
//第三步:获取数据库操作对象
stmt=cnn.createStatement();
//第四步:执行SQL语句
String sql= "select empno,ename,sal from emp";
//int count =stmt.executeUpdate(sql);执行的sql是DML语句,返回值是“影响数据库中的记录条数”
res=stmt.executeQuery(sql);//执行的DQL语句,返回的是查询结果集
//第五步:处理查询结果
while (res.next()){
//getString(查询结果集的列名称),
String empno=res.getString("empno");
String ename=res.getString("ename");
String sal=res.getString("sal");
System.out.println(empno+","+ename+","+sal);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//第六步:释放资源(为了资源一定释放,在finally语句块中关闭资源)
//遵循从小到大一次关闭
//分别对其try...catch
if (res != null) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt!= null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (cnn != null) {
try {
cnn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
上面用的jdbc.properties文件如下: