日期:2014-05-19  浏览次数:20705 次

jdbc连接sqlserver字符串如何动态指定?
Java code

URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tempdb";
String username="sa";
String password="sa";
Connection conn = DriverManager.getConnection(URL, username, password);



上面的localhost,username,password 可以让用户动态指定吗?这样就写死在程序里了,谢谢!

------解决方案--------------------
用配置文件配置
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
读取配置文件例子:
Java code

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();
        }
        
    }
    
}

------解决方案--------------------
.properties文件
------解决方案--------------------
用个 properties文件 ok
------解决方案--------------------
properties 文件放到项目文件夹下,以后就算要迁移数据库也不用改代码了,只需要改配置文件