日期:2014-05-20 浏览次数:20800 次
Properties p = new Properties(); FileInputStream is = new FileInputStream(new File("路径")); p.load(is); // 读取数据库配置 dbConn.setDriver(p.getProperty("db.driver")); dbConn.setUrl(p.getProperty("db.url")); dbConn.setUserName(p.getProperty("db.username")); dbConn.setPassword(p.getProperty("db.password")); //配置文件: db.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver db.url=jdbc:sqlserver://10.148.20.148:1433;databaseName=CI_V3R3_C01 db.username=sa db.password=wimaxci
------解决方案--------------------
db.properties文件内容: username= root password = url = jdbc:mysql://localhost:3306/study driver =com.mysql.jdbc.Driver 代码: package org.caijava.example.io ; import java.io.FileInputStream ; import java.util.Properties ; import java.io.IOException ; import java.sql.Connection ; import java.sql.DriverManager ;public class ReadProperties{ public static void main(String []args){ try{ FileInputStream fis = new FileInputStream("db.properties") ; //InputStream is = getClass().getResourceAsStream("db.properties"); Properties properties = new Properties() ; properties.load(fis) ; String uname = properties.getProperty("username").trim() ; String psw = properties.getProperty("password").trim() ; String url = properties.getProperty("url").trim() ; String driver = properties.getProperty("driver").trim() ; System.out.println("driver : "+driver +"\nname :"+ uname+" \npassword :"+psw+"\nurl:"+url) ; Class.forName(driver) ; Connection conn = DriverManager.getConnection(url,uname,psw) ; }catch(Exception e){ e.printStackTrace() ; } } }