URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tempdb";
String username="sa";
String password="sa";
Connection conn = DriverManager.getConnection(URL, username, password);
上面的localhost,username,password 可以让用户动态指定吗?这样就写死在程序里了,谢谢!

解决方案 »

  1.   

    用配置文件配置
    URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tempdb";
    String username="sa";
    String password="sa";
    这三个参数,
    文件名:“xxx.properties”
    内容:
    url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tempdb
    user=sa
    pwd=sa
    读取配置文件例子:import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    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.util.Properties;public class ConnectUtils {
    private static String url = null;
    private static String user = null;
    private static String pwd = null;
    public static Connection geConnection(){
    Connection conn=null;
    try{
    getParam("db_oracle.preperties");
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn=DriverManager.getConnection(url,user,pwd);
    }catch(Exception e){
    e.printStackTrace();
    }
    return conn;
    }
    public static void close(ResultSet rs){
    if(rs!=null){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    public static void close(PreparedStatement pstmt){
    if(pstmt!=null){
    try {
    pstmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    public static void close(Connection conn){
    if(conn!=null){
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    public static void getParam(String filename){//HERE!!!!!!!!!!!!!!!
    Properties props=new Properties();
    try {
    InputStream in=new FileInputStream(filename);
    props.load(in);
    url=(String) props.get("url");
    user=(String) props.get("user");
    pwd=(String) props.get("pwd");
    System.out.println(url+"\n"+user+"\n"+pwd);
    in.close();

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

    }

    }
      

  2.   


    public Connection getConnection(String url, String username, String password) {
    Connection conn = DriverManager.getConnection(URL, username, password);
    }
    你把这3个当参数传送进去就好了,想传啥你就传啥
      

  3.   

    那这个properties文件是开发人员手动改了?还是用户可以自定义? 这个文件放在项目文件夹中吗?
      

  4.   

    properties 文件放到项目文件夹下,以后就算要迁移数据库也不用改代码了,只需要改配置文件