jdbc 基本功

一 Statement
public class DbDemo {
	public static String url = "jdbc:oracle:thin:@127.0.0.1:1522:orcl";
	public static String usr = "yangwan";
	public static String passd = "yangwan";
	
	public void dbOption(String url,String user,String password){
		
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		String sql = "Select id,name,age From student";
		
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(ClassNotFoundException ce){
			ce.printStackTrace();
		}
		
		try{
			conn = DriverManager.getConnection(url, user, password);
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while(rs.next()){
				System.out.println("-->"+rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getInt(3));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(null != rs){
				try{
					rs.close();
				}catch(Exception e){}
			}
			
			if(null != st){
				try{
					st.close();
				}catch(Exception e){}
			}
			
			if(null != conn){
				try{
					conn.close();
				}catch(Exception e){}
			}
		}
		
		
	}
	public static void main(String[] args){
		new DbDemo().dbOption(url, usr, passd);
	}

}


二 PrepareStatement

public class PreparestatementDemo {
	public static String url = "jdbc:oracle:thin:@127.0.0.1:1999:orcl";
	public static String usr = "yangwan";
	public static String passd = "yangwan";
	
	public void dbOption(String url,String user,String password){
		Connection conn =null;
		PreparedStatement psmt =null;
		String strSql = "INSERT INTO student(id,name,age) VALUES(?,?,?)";
		
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(ClassNotFoundException ce){
			ce.printStackTrace();
		}
		
		try{
			conn = DriverManager.getConnection(url, user, password);
			psmt = conn.prepareStatement(strSql);
			psmt.setString(1, "3");
			psmt.setString(2, "James");
			psmt.setInt(3, 23);
			psmt.addBatch();
			psmt.executeBatch();
			
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(null != psmt){
				try{
					psmt.close();
				}catch(Exception e){}
			}
			
			if(null != conn){
				try{
					conn.close();
				}catch(Exception e){}
			}
		}
		
	}
	
	public static void main(String[] args){
		new PreparestatementDemo().dbOption(url, usr, passd);
		System.out.println("-->Game Over!!");
	}

}


 

你可能感兴趣的:(exception,jdbc,String,user,null,url)