使用preparedSatatement操作数据库表

执行一个完成的数据库增删改查需要下面五个步骤:
(1)因为增删改不需要结果集,所以归为一类
(2)查自成一类

1、增删改——通用格式

  1. 获取数据库连接
    数据库连接文章详解
	    //加载配置文件
        InputStream is = ClassLoader.getSystemClassloader().getResourceAsStream("jdbc.properties"); //获取系统类加载器
        Properties properties = new Properties();
        properties.load(is);
		//读取配置信息
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String url = properties.getProperty("url");
		String driverClass = properties.getProperty("driverClass");
		//获取连接
        Connection connection = DriverManager.getConnection(url,user,password);
  1. 获取preparedStatement的实例
	String sql = "update student set name = ? where id = ?";
	PreparedStatement ps = connection.preparedStatement(sql); //这个就是perparedStatement实例
  1. 填充占位符
	ps.setObject(1,"chen");
	ps.setObject(2,2);
  1. 执行sql语句
	ps.execute();
  1. 关闭资源
	connection.close();
	ps.close();

2、查——通用格式

    // 通用的针对于不同表的查询:返回一个对象 (version 1.0)    
    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
    
    
        Connection conn = null;        
        PreparedStatement ps = null;        
        ResultSet rs = null;        
        try {
    
                
        // 1.获取数据库连接            
        conn = JDBCUtils.getConnection();
            // 2.预编译sql语句,得到PreparedStatement对象           
             ps = conn.prepareStatement(sql);
            // 3.填充占位符            
            for (int i = 0; i < args.length; i++) {
    
                    
            	ps.setObject(i + 1, args[i]);            
            }
            // 4.执行executeQuery(),得到结果集:
            ResultSet rs = ps.executeQuery();
            // 5.得到结果集的元数据:ResultSetMetaData           
             ResultSetMetaData rsmd = rs.getMetaData();
            // 6.1通过ResultSetMetaData得到columnCount,columnLabel;通过ResultSet得到列值            
            int columnCount = rsmd.getColumnCount();            
            if (rs.next()) {
    
                   
             T t = clazz.newInstance();                
             for (int i = 0; i < columnCount; i++) {
    
    
             	// 遍历每一个列
            	 // 获取列值                    
				Object columnVal = rs.getObject(i + 1);                    
				// 获取列的别名:列的别名,使用类的属性名充当                    
				String columnLabel = rsmd.getColumnLabel(i + 1);                    
				// 6.2使用反射,给对象的相应属性赋值                    
				Field field = clazz.getDeclaredField(columnLabel);
				field.setAccessible(true);                    
				field.set(t, columnVal);
              }
                return t;
            }        
       } catch (Exception e) {
    
    
          e.printStackTrace();        
       } finally {
    
                
          	// 7.关闭资源            
          	JDBCUtils.closeResource(conn, ps, rs);       
       }
        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_45151059/article/details/113784992