java 通过读取properties文件连接数据库

1.创建数据库配置文件 dbconfig.properties(项目根目录下)。

#oracle数据库连接配置
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@(description=(address_list= (address=(host=服务器IP) (protocol=tcp)(port=1521)))(connect_data=(service_name= 数据库名称)))
jdbc.username=CCMMESPRD
jdbc.password=CCMMESPRD

2.通过Properties加载dbconfig.properties文件内容。

public class DBConfigure 
{
      private static final Properties props=new Properties();
      
      static
      {
    	    try 
    	    {
    	    	InputStream input = DBConfigure.class.getResourceAsStream("/dbconfig.properties");
    	    	props.load(input);
			} catch (Exception ex) 
			{
				Logger.getLogger(DBConfigure.class.getName()).log(Level.SEVERE,
						"无法加载配置属性文件! ", ex);
			}    	  
      }

	public static String getProperty(String propName) {
		return props.getProperty(propName);
	}
	
	public static void setProperty(String propname, String propValue) {
		props.setProperty(propname, propValue);
	}
}

3.获取数据库连接

public DBConnection() 
	{
		driver = DBConfigure.getProperty("jdbc.driverClassName");
		conStr = DBConfigure.getProperty("jdbc.url");
		username = DBConfigure.getProperty("jdbc.username");
		password = DBConfigure.getProperty("jdbc.password");
		
		System.out.println("正在加载驱动程序...");
		try 
		{
		     Class.forName(driver);
		} catch (ClassNotFoundException ex) {
		     System.out.println("加载驱动程序错误!");
		     System.out.println(ex.getMessage());
		}
		System.out.println("成功加载驱动程序!");
	}
	//获得数据库连接
	public Connection getConnection() 
	{
		Connection con = null;
		try {
			con = DriverManager.getConnection(conStr, username, password);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return con;
	}
	
}

4.在DAO层操作数据库

public class StudentDao 
{
	DBConnection dbCon = null;

	public StudentDao() 
	{
		dbCon = new DBConnection();
	}
	
	public int AddStud(CcmStudent stud)
	{
		Connection con = null;
		PreparedStatement ps = null;
		String sqlStr = "insert into CCM_STUDENT values(?,?,?,?,?,?)";
		int effectRows = 0;
		try 
		{
			con = dbCon.getConnection(); // 获得数据库连接
			ps = con.prepareStatement(sqlStr);
			ps.setString(1, stud.getStud_No());
			ps.setString(2, stud.getStud_Name());
			ps.setString(3, stud.getMajor());
			ps.setString(4, stud.getSex());
			ps.setDate(5, stud.getBirthday());
			ps.setString(6, stud.getNote());
			
			effectRows = ps.executeUpdate();//执行插入操作
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}finally
		{
			try 
			{
				if (con != null) 
					con.close();
				if (ps != null) 
					ps.close();
			} catch (Exception e2) {
				
			}
		}
		return effectRows;		
	}
}

注意:项目必须导入oracle数据库jdbc驱动嫁包:ojdbc6.jar

posted on 2024-10-11 09:11  willian知识库  阅读(98)  评论(0)    收藏  举报