标签:replace com thread alt http 顺序 连接数据库 getc javaweb
注意:web运行读取要把配置文件放在WEB-INF下面
Driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://192.168.33.170;DatabaseName=Platform_U_v3.0
userName=xxzx
password=xxzx
从上到下依次为驱动 数据库连接 账号 密码
package com.bowei.utl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; 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 JdbcUtl { // 数据库驱动 private static String Driver = ""; // 数据库地址 private static String url = ""; // 数据库用户名 private static String userName = ""; // 数据库密码 private static String password = ""; static { Properties p = new Properties(); try { // 通过相对路径加载文件 String path=Thread.currentThread().getContextClassLoader().getResource("").toString(); path=path.replace(‘/‘, ‘\\‘); // 将/换成\ path=path.replace("file:", ""); //去掉file: path=path.replace("classes\\", ""); //去掉class\ path=path.substring(1); //去掉第一个\,如 \D:\JavaWeb... path+="/sof/jdbc.properties"; p.load(new FileInputStream(new File(path))); // 用getProperty方法通过关键字获取信息 Driver = p.getProperty("Driver"); url = p.getProperty("url"); userName = p.getProperty("userName"); password = p.getProperty("password"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String getDriver() { return Driver; } public static void setDriver(String driver) { Driver = driver; } public static String getUrl() { return url; } public static void setUrl(String url) { JdbcUtl.url = url; } public static String getUserName() { return userName; } public static void setUserName(String userName) { JdbcUtl.userName = userName; } public static String getPassword() { return password; } public static void setPassword(String password) { JdbcUtl.password = password; } // 获取数据库连接 public static Connection getConn() { Connection conn = null; try { // 加载驱动 Class.forName(Driver); // 获取数据库连接 conn = DriverManager.getConnection(url, userName, password); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } // 关闭数据库资源 public static void closeAll(ResultSet rs, Statement stat, Connection conn) { /* 分别按顺序关闭数据库的结果集资源,Statement 对象资源以及Connection 连接数据库对象 */ if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stat != null) { try { stat.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
标签:replace com thread alt http 顺序 连接数据库 getc javaweb
原文地址:http://www.cnblogs.com/txl401/p/6074508.html