JDBC--头歌(educoder)实训作业题目及答案

目录

Java高级特性 - JDBC(上)

第1关:JDBC连接数据库

第2关:JDBC对表中数据的操作

第3关:JDBC事务

Java高级特性 - JDBC(下)

第1关:指定类型JDBC封装

第2关:泛型JDBC封装

JDBC基础编程练习

第1关:JDBC更新员工密码

第2关:JDBC查询员工信息


Java高级特性 - JDBC(上)

第1关:JDBC连接数据库

package jdbc;

import java.sql.*;

public class jdbcConn {
    public static void getConn() {
        /**********    Begin   **********/
        try {
			//1.注册驱动


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }a
        /**********    End   **********/


        /**********    Begin   **********/
        Connection conn = null;
        Statement statement = null;
        //2.建立连接并创建数据库和表




        

        /**********    End   **********/
        finally {
            try {
                if(statement!=null)
                    statement.close();
                if(conn!=null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

第2关:JDBC对表中数据的操作

package jdbc;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class jdbcInsert {
    public static void insert(){
		/**********   Begin  **********/
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver" );

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
		/**********   End   **********/
		Connection conn = null;
		PreparedStatement statement = null;
		/**********   Begin  **********/
        //连接并插入数据
		try{
		conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql_db","root","123123");
        PreparedStatement s = conn.prepareStatement("insert into student values(?,?,?,?)");
        s.setInt(1,1);s.setString(2,"张三");s.setString(3,"男");s.setInt(4,19);
        s.executeUpdate();
        s.setInt(1,2);s.setString(2,"李四");s.setString(3,"女");s.setInt(4,18);
        s.executeUpdate();
        s.setInt(1,3);s.setString(2,"王五");s.setString(3,"男");s.setInt(4,20);
        s.executeUpdate();
        s=conn.prepareStatement("select * from student");
        ResultSet r = s.executeQuery();
        while(r.next()){
            System.out.println(r.getString(1)+" "+r.getString(2)+" "+r.getString(3)+" "+r.getString(4));
        }
		} catch (SQLException e) {
            e.printStackTrace();
        }



        
		/**********   End   **********/
		finally {
            try {
                if (statement != null)
                    statement.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

第3关:JDBC事务

package jdbc;
import java.sql.*;
public class jdbcTransaction {
public static void transaction(){
    try {
        Class.forName("com.mysql.jdbc.Driver" );
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection conn = null;
    PreparedStatement ps = null;
    /**********  Begin   **********/
    //连接数据库并开启事务
    String url = "jdbc:mysql://localhost:3306/mysql_db";
    try {
        conn = DriverManager.getConnection (url,"root","123123" );
        conn.setAutoCommit(false);//关闭自动提交开启事务
        ps = conn.prepareStatement("insert into student(id,name,sex,age) values(4,'赵六','女',21)");
        ps.executeUpdate();
        conn.commit();//提交事务
        ps = conn.prepareStatement("insert in student(id,name,sex,age) values(5,'钱七','男',18)");
        ps.executeUpdate();
        conn.commit();//提交事务
    } catch (SQLException e) {
        try {
            //事务回滚
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
    /**********  End   **********/
    finally {
        try {
            if(ps!=null)
                ps.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
}
}

Java高级特性 - JDBC(下)

第1关:指定类型JDBC封装

package step1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import test.News;
public class JDBCUtils {
    /**
     * 连接数据库
     */
    private static Connection getConnection() {
        Connection conn=null;
        /**********  Begin  **********/
        String url="jdbc:mysql://localhost:3306/mysql_db";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root","123123");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        /**********   End   **********/
        return conn;
    }
    /**
     * 更新数据方法
     * @param news
     * @throws SQLException
     */
    public void update(News news) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        /**********  Begin  **********/
        String sql = "update news set title=?,author_name=? where id=?";
        try{
            ps = conn.prepareStatement(sql);
            ps.setString(1, news.getTitle());
            ps.setString(2, news.getAuthor_name());
            ps.setInt(3, news.getId());
            ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
            throw new SQLException("更新数据失败");
        }finally{
            close(null, ps, conn);
        }    
        /**********  End  **********/
    }
    /**
     * 查询所有数据
     * @return
     * @throws SQLException
     */
    public List findAll() throws SQLException {
        Connection conn =  getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        News news = null;
        List newsList = new ArrayList();
        /**********  Begin  **********/
        String sql = "select * from news";
        try{
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                news = new News();
                news.setId(rs.getInt(1));
                news.setTitle(rs.getString(2));
                news.setAuthor_name(rs.getString(3));
                newsList.add(news);
            }
        }catch(SQLException e){
            e.printStackTrace();
            throw new SQLException("查询所有数据失败");
        }finally{
            close(rs, ps, conn);
        }
        /**********  End  **********/
        return newsList;
    }
    /**
     * 删除方法
     * @param id
     * @throws SQLException
     */
    public void delete(int id) throws SQLException{
        Connection conn = getConnection();
        PreparedStatement ps = null;
        /**********  Begin  **********/
        String sql = "delete from news where id=?";
        try{
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
            throw new SQLException(" 删除数据失败");
        }
        finally{
            close(null, ps, conn);
        }        
        /**********  End  **********/
    }
    /**
     * 增加对象
     * @param news
     * @throws SQLException
     */
     
    public void insert(News news) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        String sql = "insert into news(id,title,author_name)values(?,?,?)";
        try{

            ps = conn.prepareStatement(sql);
            ps.setInt(1, news.getId());
            ps.setString(2, news.getTitle());
            ps.setString(3, news.getAuthor_name());
            ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
            throw new SQLException("添加数据失败");
        }finally{
           close(null, ps, conn);
        }
    }
    /**
     * 根据id查询对象
     * @param id
     * @return
     * @throws SQLException
     */
    public News findById(int id) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        News news = null;
        String sql = "select * from news where id=?";
        try{

            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if(rs.next()){
            	news = new News();
            	news.setId(id);
            	news.setTitle(rs.getString(2));
            	news.setAuthor_name(rs.getString(3));
            }
        }catch(SQLException e){
            e.printStackTrace();
            throw new SQLException("根据ID查询数据失败");
        }
        finally{
            close(rs, ps, conn);
        }
        return news;
    }

    /**
     * 关闭数据库连接
     * @param rs
     * @param ps
     * @param conn
     */
    public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
    	try {
    		if(rs!=null)rs.close();
    		if(ps!=null)ps.close();
    		if(conn!=null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}	

第2关:泛型JDBC封装

package step2;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JDBCUtils {
	private static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url="jdbc:mysql://localhost:3306/mysql_db";
		Connection conn=null;
		try {
			conn = DriverManager.getConnection(url, "root","123123");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	/**
     * 类名对应表,属性对应字段
     * @param obj  传入的对象
     * @return
     */
    public void insert(Object obj) {
    	Connection conn = getConnection();  //连接数据库
    	PreparedStatement ps = null;
    	/********** Begin **********/
    	//获取obj的Class
        Class c = obj.getClass();        
        //利用StringBuffer进行插入SQL语句的构造
        StringBuffer sb1 = new StringBuffer("insert into "+ c.getSimpleName() +"(");  //通过反射获取类名映射表名
        StringBuffer sb2 = new StringBuffer(" values(");  //注意前面要多加一个空格 否则sql将连在一起
        Field[] field = c.getDeclaredFields();            //获取对象的属性数组
        for(int i = 0; i < field.length; i++) {           //遍历属性构造SQL语句
            if(i != field.length-1) {
                sb1.append(field[i].getName()).append(",");
                sb2.append("?,");
            }else {
                sb1.append(field[i].getName()).append(")");
                sb2.append("?);");
            }
        }
        String sql = sb1.append(sb2).toString();
        try {
            ps = conn.prepareStatement(sql);
            for(int i = 0; i < field.length; i++) {    
                field[i].setAccessible(true);                    //设置属性的可访问性,可以访问私有属性
                try {                                            //通过Field的get(Object)方法获取Object对象的属性值
                    ps.setObject(i+1, field[i].get(obj));        //对预编译的SQL语句中的?进行赋值
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            ps.execute();        //执行SQL
        }
        /********** End **********/
        catch (SQLException e) {
            e.printStackTrace();
        }finally {    
            close(null,ps,conn);
        }
    }
    /**
     * 通过对象的Class获取对应表中的所有记录
     * @param c
     * @return
     */
    public  List selectAll(Class c) {
    	Connection conn = getConnection();
    	List list = new ArrayList();          
    	PreparedStatement ps = null;
    	ResultSet rs = null;
    	/********** Begin **********/
       String sql = "select * from "+ c.getSimpleName()+";";        //通过反射获取类名对应表名构造SQL语句
        Field[] field = c.getDeclaredFields();                        //通过反射获取所有属性
        try {
            ps = conn.prepareStatement(sql);            
            rs = ps.executeQuery();                     
            while(rs.next()) {
                T obj = c.newInstance();                //通过反射构造一个T类型的实例
                for(int i = 0; i < field.length; i++) {        
                    field[i].setAccessible(true);                            //设置可以访问私有属性
                    field[i].set(obj, rs.getObject(field[i].getName()));    //通过属性名获取结果集中的值赋值到实例对象中
                }
                list.add(obj);                                                //将实例对象添加到list集合
            }
         }
        /********** End **********/ 
        catch (Exception e) {
            e.printStackTrace();
        }finally {    
            close(rs,ps,conn);
        }
        return list;
    }
    /**
     * 通过主键(默认第一个属性)删除对象
     * @param obj
     * @return
     */
    public void delete(Object obj) {
    	Connection conn = getConnection();
    	PreparedStatement ps = null;
    	/********** Begin **********/
       //获取obj的Class
        Class c = obj.getClass();        
        //构造删除的SQL语句
        StringBuffer sb = new StringBuffer("delete from ");
        sb.append(c.getSimpleName()).append(" where ");
        //获取对象属性数组
        Field[] field = c.getDeclaredFields();
        //设置第一个属性的可访问性
        field[0].setAccessible(true);
        //获取第一个属性的属性名构造删除sql
        sb.append(field[0].getName()).append("=?");
        String sql = sb.toString();
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1, field[0].get(obj));    
            ps.execute();
        } 
        /********** End **********/
        catch (Exception e) {
            e.printStackTrace();
        }finally {    
            close(null,ps,conn);
        }
    }
    /**
     * 模拟jdbc的更新操作,默认第一个属性为主键
     * @param obj
     * @return
     */
    public void update(Object obj) {
    	Class c = obj.getClass();//获取obj的Class
    	StringBuffer sb = new StringBuffer("update "+ c.getSimpleName() +" set ");//利用StringBuffer进行修改SQL语句的构造
    	Field[] field = c.getDeclaredFields();//通过反射获取对象的属性数组
    	for(int i = 1; i < field.length; i++) {
    		if(i != field.length-1) {    //判断是否为最后一个属性,若不是则后增加逗号
    			sb.append(field[i].getName()).append("=?,");
    		}else {    //若为最后一个属性则添加 where
    			sb.append(field[i].getName()).append("=? where ");
    		}
    	}
    	//默认第一个属性为主键,切更改时通过第一个属性进行更改
    	sb.append(field[0].getName() + "=?");
    	String sql = sb.toString()+";";
    	Connection conn = getConnection();//获取连接对象
    	PreparedStatement ps = null;
    	try {
    		ps = conn.prepareStatement(sql);
    		for(int i = 1; i < field.length; i++) {
    			field[i].setAccessible(true);//设置可以访问私有属性
    			ps.setObject(i, field[i].get(obj));//对预编译的SQL语句中的 ? 进行赋值
    		}
    		field[0].setAccessible(true);
    		ps.setObject(field.length, field[0].get(obj));
    		ps.execute();//执行sql语句
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally {
    		close(null,ps,conn);//关闭连接数据
    	}
    }
    public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
    	try {
    		if(rs!=null) rs.close();
    		if(ps!=null) ps.close();
    		if(conn!=null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
    public  Object selectById(Class c,int id) {
        String sql = "select * from "+ c.getSimpleName()+" where id="+id;    
        Field[] field = c.getDeclaredFields();
        Connection conn = getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Object obj=null;
        try {
            ps = conn.prepareStatement(sql);  
            rs = ps.executeQuery(); 
            obj = c.newInstance();
            while(rs.next()) {
                for(int i = 0; i < field.length; i++) {      
                    field[i].setAccessible(true);           
                    field[i].set(obj, rs.getObject(field[i].getName()));   
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {    
            close(rs,ps,conn);
        }
        return obj;
    }
}

JDBC基础编程练习

第1关:JDBC更新员工密码

package step1;

import java.sql.*;

public class UpdatePass {
	// 修改数据
	public static void updateDB() {

		/********* Begin *********/

		// 第一步:加载驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}

		// 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
		// 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf8";
			String user = "root";
			String password = "123123";
			conn = DriverManager.getConnection(url, user, password);
			// 第三步:建立statement对象

			String sql = "update employee set password='hello' where sex='女'";
			ps = conn.prepareStatement(sql);

			// 第四步:修改数据
			ps.execute();
			// 第五步:关闭statement对象和连接对象
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}

		/********* End *********/

	}

}

第2关:JDBC查询员工信息

package step1;

import java.sql.*;

public class QueryPass {

	// 查询数据代码不用上实验报告
	public static void queryDB() {

		/********* Begin *********/
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			// 第一步:加载驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
			// 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8
			String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf8";
			String user = "root";
			String password = "123123";
			conn = DriverManager.getConnection(url, user, password);

			// 第三步:建立statement对象
			String sql = "select * from employee";
			ps = conn.prepareStatement(sql);

			ResultSet rs = ps.executeQuery();
			// 第四步:查询数据

			while (rs.next()) {
				String no = rs.getString(1);
				String name = rs.getString(2);
				Object password1 = rs.getString(3);
				Object sex = rs.getString(4);
				double salary = rs.getDouble(5);
				System.out.println("no:" + no + "\tname:" + name + "\tpassword:" + password1 + "\tsex:" + sex
						+ "\tsalary:" + salary);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 第五步:关闭statement对象和连接对象

			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}



		/********* End *********/
	}
}

你可能感兴趣的:(java)