关于JdbcUtils工具类,很久之前就用过,好记性不如烂笔头。
在JdbcUtils中无所谓就是两个方法
1–>连接资源
2–>释放资源
直接上代码
package cn.tong.jdbc.utils;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
// 在这个工具类里面,提供两个方法一个是获取链接对象,一个是关闭资源
public class JdbcUtils {
// 注册驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 连接资源
public static Connection getConnection() throws Exception{
// 定义url
String url = "jdbc:mysql:///People";
// 定义user
String user = "root";
// 定义密码
String passWord = "123456";
Connection con = (Connection) DriverManager.getConnection(url,user,passWord);
return con;
}
// 释放资源
public static void close(ResultSet rs,Statement st, Connection con ) throws SQLException{
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
public static void main(String[] args) throws Exception {
System.out.println(getConnection());
}
}
上述代码是JdbcUtils的工具类
下面是测试类代码
package cn.tong.test;
import java.lang.Thread.State;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import cn.tong.jdbc.utils.JdbcUtils;
public class JdbcUtilsTest {
public static void main(String[] args) throws Exception {
Connection con = JdbcUtils.getConnection();
Statement statement = (Statement) con.createStatement();
// 写sql语句
String sql = "INSERT INTO `Students` (`name`, `sex`, `age`, `tel`, `classname`) VALUES ('pangzi', 'nan', '20', '111', '0')";
// 执行sql语句
int result = statement.executeUpdate(sql);
System.out.println(result);
// 关闭资源
JdbcUtils.close(null, statement, con);
}
}
这样使用工具类是管理更加方便。