jdbc知识积累--java基础

JDBC(Java Data Base Connectivity,java数据库连接)是一种Java API;它封装了对各种不同的数据库访问的统一接口,使得开发人员在编写同一标准的代码就能访问不同的数据库。不过随着jdbc使用越来越频繁,在考虑到效率和易用性时,它被作为基础接口来建立各种数据库高级接口,现在很多中间件就是基于jdbc的。

使用jdbc三部曲:加载驱动、建立连接、操作数据库

public class JDBCServer {
/**
 * jdbc通用伪代码
 * 	Connection con = DriverManager.getConnection("jdbc:odbc:wombat","login","password");  
	Statement stmt = con.createStatement();  
	ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");  
	while (rs.next()) {  
		int x = rs.getInt("a");  
		String s = rs.getString("b");  
		float f = rs.getFloat("c");  
	}*/

	/**
	 * 获取连接
	 * @param drivername:驱动类
	 * @param url		:连接url
	 * @param username	:连接用户名
	 * @param password	:连接密码
	 * @return
	 * jdbc连接oracle:使用驱动程序添加包:ojdbc14.jar
	 	String drivername = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@//172.16.89.145:1521/cgw";
		String username = "dzzwpt";
		String password = "dzzwpt";
	 * 
	 */
	public Connection getConnection(String drivername,String url,String username,String password){
		try {
			Class.forName(drivername);
			Connection conn = DriverManager.getConnection(url, username, password);
			return conn;
		} catch (ClassNotFoundException e) {
			System.out.println("can not find the Driver class!");
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		//oracle连接
		JDBCServer server = new JDBCServer();
		String drivername = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@//172.16.89.145:1521/cgw";
		String username = "dzzwpt";
		String password = "dzzwpt";
		Connection conn = server.getConnection(drivername, url, username, password);
		try {
			Statement stmt = conn.createStatement();
			stmt.executeQuery("select * from ta_jcdz t where t.by1='money'");
			ResultSet rst = stmt.getResultSet();
			for(;rst.next();){
				System.out.println(rst.getString(3));
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}

正在知识积累中,请各位大侠指点... 

你可能感兴趣的:(java基础)