连接数据库方法类

来源:互联网 发布:unity3d 弧线运动 编辑:程序博客网 时间:2024/04/29 08:25
public class ConnSQL {public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {    setConfig();    Connection conn =  getConn();    if(conn != null){        System.out.println("success");        conn.close();    }}/** * 获取sqlservice数据库连接 * @return * @throws ClassNotFoundException * @throws SQLException * @throws IOException */public static Connection getConn() throws ClassNotFoundException, SQLException, IOException{    //从配置文件中读取信息    FileInputStream fis = new FileInputStream("configuration.prop");    Properties config = new Properties();    config.load(fis);    String DBDriver = config.getProperty("DBDriver");    String DBUrl = config.getProperty("DBUrl");    String DBUsername = config.getProperty("DBUsername");    String DBPassword = config.getProperty("DBPassword");    //获取连接    Class.forName(DBDriver);    Connection conn =  DriverManager.getConnection(DBUrl, DBUsername, DBPassword);    return conn;}/** * 设置sqlservice的配置信息 * @throws IOException */public static void setConfig() throws IOException{    Properties configuration = new Properties();    FileWriter fw = new FileWriter("configuration.prop");    //设置配置信息    configuration.setProperty("DBDriver", "com.microsoft.sqlserver.jdbc.SQLServerDriver");    configuration.setProperty("DBUrl","jdbc:sqlserver://localhost:1433;integratedSecurity=true;DatabaseName=supermarket");    configuration.setProperty("DBUsername","log1");    configuration.setProperty("DBPassword", "123");    configuration.store(fw,"sql's configuration");    System.out.println("success");}}

0 0