jdbc.properties,以及读取配置信息

public void getValue()
{
//System.out.println("..//"+System.getProperty("user.dir")+"//webapps");

try {
String path = this.getClass().getClassLoader().getResource("/").getPath();
String url = path.replaceAll("%20", " ");
FileInputStream fis = new FileInputStream(url+"config.properties");
Properties prop = System.getProperties();
try {
prop.load(fis);
//赋值
this.DRIVER = prop.getProperty("driver");
this.URL = prop.getProperty("url");
this.USER = prop.getProperty("user");
this.PASSWORD =prop.getProperty("password");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


.jdbc.properties
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://Ip地址:1433;databaseName=test
user=test
password=test

2.一个Servlet
import java.io.PrintStream;
import java.sql.*;
import java.util.ResourceBundle;

public class DBOperator
{

public DBOperator()
{
}

public static void main(String args[])
{
Connection con = getConnection();
System.out.println("connection success");
closeConnection(con);
System.out.println("close success");
}

public static Connection getConnection()
{
try
{
return DriverManager.getConnection(url, user,

password);
}
catch(SQLException e)
{
e.printStackTrace();
}
return null;
}

public static void closeConnection(Connection con)
{
try
{
if(con != null)
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}

private static String url;
private static String user;
private static String password;

static
{
ResourceBundle bundle = ResourceBundle.getBundle("路径");
try
{
Class.forName(bundle.getString("driver"));
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
url = bundle.getString("url");
user = bundle.getString("user");
password = bundle.getString("password");
}
}

你可能感兴趣的:(ext)