JDBC串連資料庫的工具包代碼

來源:互聯網
上載者:User

package donghongyu.tk.news.util;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;//進行串連,public class JdbcUtil {private  static Connection conn;private JdbcUtil() {super();// TODO Auto-generated constructor stub}//返回連線物件public  static synchronized Connection getConn() {if (conn == null) {try {// 載入驅動檔案 Class.forName("com.mysql.jdbc.Driver");// 將屬性檔案載入File file = new File("src/jdbc.properties");// 將檔案轉化為輸入資料流InputStream is = new FileInputStream(file);// 建立屬性對象Properties prop = new Properties();// 將屬性流程載入到屬性對象中prop.load(is);// 建立串連從屬性檔案取出相應值串連conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"), prop.getProperty("pass"));} catch (ClassNotFoundException | IOException | SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return conn;}//關閉資源就行釋放public static void release(Statement pstmt, ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (pstmt != null) {try {pstmt.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.