通過讀取properties檔案動態生成對資料庫的連線

不設限發表於2011-12-11

properties檔案:db.properties

#Oracle mysql db info
db_url_oracle = jdbc:oracle:thin:@127.0.0.1:1521:ora9
db_url_mysql = jdbc:mysql://localhost/dandan?characterEncoding=utf-8
username = root
password = dada


獲取對mysql的連線並操作:


import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;


public class MysqlConn {
public static Connection getConn() throws Exception {
//新建物件
Properties ps=new Properties();
//獲取輸入流
FileInputStream fis=new FileInputStream("src\\chapter18\\properties\\db.properties");
//把流載入到記憶體中
ps.load(fis);
//關閉流
fis.close();

//獲取資料庫url
String url=ps.getProperty("db_url_mysql");
//獲取使用者名稱
String user=ps.getProperty("username");
//獲取密碼
String password=ps.getProperty("password");
//獲取連線
Connection conn=DriverManager.getConnection(url,user,password);
return conn;
}

public static void main(String[] args) throws Exception {
//載入驅動
Class.forName("org.gjt.mm.mysql.Driver");
//獲取連線
Connection conn=MysqlConn.getConn();
//建立statement
Statement stmt=conn.createStatement();
//執行操作
ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next()) {
System.out.println("id: "+rs.getInt(1)+"\tname: "+rs.getString(2)+
"\tsex: "+rs.getString(3)+"\tgrade: "+rs.getString(4));
}
rs.close();
stmt.close();
conn.close();
}
}


獲取對Oracle的連線並操作


import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;


public class OracleConn {
public static Connection getConnection() throws Exception {
//建立Properties物件
Properties ps=new Properties();
//建立讀取流
FileInputStream fis=new FileInputStream("mydb.properties");
ps.load(fis);
fis.close();

String url=ps.getProperty("db_url_oracle");
String userName=ps.getProperty("userName");
String password=ps.getProperty("password");

Connection conn=DriverManager.getConnection(url,userName,password);
return conn;
}

public static void main(String[] args) throws Exception {
//1.載入驅動 2.獲取連線 3.獲取statement 4.執行操作
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=OracleConn.getConnection();
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next()){
System.out.print("stuId: " + rs.getInt(1));
System.out.print("\name: " + rs.getString(2));
System.out.println("\tgrade: " + rs.getString(3));   
}
rs.close();
stmt.close();
conn.close();
}
}

相關文章