博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JDBC-查询-添加

Posted on 2019-10-22 22:21  淼哥学习园地  阅读(160)  评论(0)    收藏  举报

 

工具类JDBCutils提供俩个操作:

(1) 连接数据库

public static Connection getConnction5() throws Exception
	{
		//读取配置文件中的四个基本信息
		
		InputStream is=  ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
		
		Properties pros=new Properties();
		pros.load(is);
		
		String url=pros.getProperty("url");
		String user=pros.getProperty("user");
		String password=pros.getProperty("password");
		
		//加载驱动:调用静态代码,注册了Driver驱动
		Class.forName("com.mysql.jdbc.Driver");
				
		//获取连接
		Connection conn=DriverManager.getConnection(url,user,password);
		System.out.println(conn);
		return conn;
		}

  

(2)释放资源

//关闭资源::  连接和statement
	public static void closeResource(Connection conn,PreparedStatement ps)
	{
		try {
			if(ps!= null)
			{
				ps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			if(conn!= null)
			{
				conn.close();
			}
		} catch ( Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

  数据库的查询操作:

1.通用查询一 :  返回一个对象

  

public <T> T getInstance(Class<T> clazz,String sql,Object ...args){
		
		Connection conn =null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		try {
			conn=JDBCUtils.getConnction5();
			ps=(PreparedStatement) conn.prepareStatement(sql);
			
			for(int i=0;i<args.length;i++)
			{
				ps.setObject(i+1,args[i]);
			}
			
			rs=ps.executeQuery();
			
			ResultSetMetaData rsmd=(ResultSetMetaData) rs.getMetaData();
			int columnCount=rsmd.getColumnCount();
			
			if(rs.next()){
				T t=clazz.newInstance();  //反射
				
				for(int i=0;i<columnCount;i++){
					Object columValue=rs.getObject(i+1);
					String columnLable1=rsmd.getColumnLabel(i+1);
					
					java.lang.reflect.Field field=clazz.getDeclaredField(columnLable1);
					field.setAccessible(true);
					field.set(t,columValue);
				}
				
				return t;
			
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}

 2. 更新操作:

public int  update(String sql,Object ...args)
	{
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			 conn=JDBCUtils.getConnction5();
			
			 ps=(PreparedStatement) conn.prepareStatement(sql);
			for(int i=0;i<args.length;i++){
				ps.setObject(i+1, args[i]);
			}
			
			return  ps.executeUpdate();  //返回影响了多少条数据
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JDBCUtils.closeResource(conn, ps);
		}
		
		return 0;
	}