日期:2014-05-16 浏览次数:20461 次
最近整理一下以前使用的java连接数据库的方法,先是采用Properties文件链接SQL Server数据库。
?
数据库连接类:DBUtil.java
package com.jdbc.jdbcConnection; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 使用Properties 的方式加载数据库连接文件 * * version 1.0 * @author zjc * @since 1.0 */ public class DBUtil { private final static Properties props = new Properties(); static { InputStream input = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); try { props.load(input); Class.forName(props.getProperty("driverClass")); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } String url = props.getProperty("url"); String user = props.getProperty("user"); String password = props.getProperty("password"); Connection conn = null; Statement stmt = null; PreparedStatement pst = null; ResultSet rs = null; public Connection getConnection() { try { conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); } return null; } public Statement getStatement() { getConnection(); try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } return stmt; } public PreparedStatement getPreparedStatement(String sql) { getConnection(); try { pst = conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return pst; } public ResultSet getReslutSet(String sql) { getStatement(); try { rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } public boolean update(String sql){ getStatement(); boolean flag = false; try { stmt.execute(sql); flag = true; } catch (SQLException e) { e.printStackTrace(); } return flag; } public void close() { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
资源文件:jdbc.properties
driverClass=net.sourceforge.jtds.jdbc.Driver url=jdbc:jtds:sqlserver://127.0.0.1:1433/db user=username password=password
?
将jdbc.properties 放到项目src下,配置成功。