JDBC工具类的制作---复刻至com.itheima
1.jdbc工具类的制作 需要用到properties文件
文件中的驱动包需要手动导入至lib目录:
至此准备措施已经就位,可以编写jbdc工具类的主代码了:
public class jdbc_util {
private static String url;
private static String user;
private static String password;
public static String driver;
/**
文件只需要读取一次,就可以获取这些值,使用静态代码块
*/
static {
/**
* 读取资源文件 jdbc.properties,获取值
*/
try {
/**
* 1.创建peoperties集合类
*/
Properties pro = new Properties();
/**
* 2.加载文件
*/
//获取src路径下的文件的方式-->classloader 类加载器
ClassLoader classLoader = jdbc_util.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
System.out.println(path);
pro.load(new FileReader(path));
/**
* 3.获取数据,赋值
*/
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
/**
* 4.注册驱动
*/
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取链接,返回链接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
在使用jdbc时就可以带来便利:
package util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import static util.jdbc_util.driver;
/**
* 在数据库表中 , 添加一条记录 使用 insert 语句
*/
public class jdbc_Dao_add {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
/** 1. 注册驱动*/
Class.forName(driver);
/** 2.定义sql* 在students 表中添加一条记录*/
String sql = "insert into students values(5,'青铜峡',28,'男')";
/** 3.获取 connection 对象 */
conn = jdbc_util.getConnection();
/** 4.获取执行 sql 的对象 statement */
stmt = conn.createStatement();
/** 5. 执行sql */
int count = stmt.executeUpdate(sql); //影响的行数
// rs = stmt.executeQuery(sql);
System.out.println(count);
/** 6. 处理结果 */
if (count > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
/** 释放资源 避免内存溢出 及 空指针异常 */
jdbc_util.close(rs,stmt,conn);
}
}
}