通过JDBC链接数据库的操作很常见,下面介绍一种初级的使用JDBC创建数据库连接和释放数据库连接的方式。该方式单线程下没有问题,多线程环境下会出现类似于A线程释放了B线程的连接错误。
db.properties配置文件内容:
className=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day16
user=root
password=123456
DBUtil连接工具类:
public class DBUtil { private static String className; private static String url; private static String user; private static String password; static{ try{ InputStream in = DBUtil.class.getClassLoader() .getResourceAsStream("db.properties"); Properties props = new Properties(); props.load(in); className = props.getProperty("className"); url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); Class.forName(className); }catch(Exception e){ e.printStackTrace(); } } public static Connection getConnection()throws Exception{ return DriverManager.getConnection(url,user,password); } public static void release(Connection conn,Statement stmt, ResultSet res){ if(res != null){ try{ res.close(); }catch(Exception e){ e.printStackTrace(); }finally{ if(stmt != null){ try{ stmt.close(); }catch(Exception e){ e.printStackTrace(); }finally{ if(conn != null){ try{ conn.close(); }catch(Exception e){ e.printStackTrace(); } } } } } } } }
上述工具类可以完成简单的单线程环境下MySQL数据库建立连接和释放链接的功能,多线程环境下请勿使用该工具类。可能会造成链接不够用,效率缓慢,或者线程安全等一些列问题。
注:文章属作者原创,如果转发,请务必标注出处:https://www.jinnianshizhunian.vip