Java 数据库操作

JDBC(Java DataBase Connection)是根据Java访问数据库。

PreparedStatement 和 Statement一样,PreparedStatement也是用来执行sql语句的。

PreparedStatement的优点1-参数设置

Statement 需要进行字符串拼接,可读性和维护性比较差

String sql = "insert into hero values(null "," + " '年龄' "+ "," +20.0f+ "," +50);

PreparedStatement 使用参数设置,可读性好,不易犯错

String sql = "insert into hero values(null,?,?,?)";

PreparedStatement的优点2-性能表现

PreparedStatement有预编译机制,性能比Statement更快

PreparedStatement的优点3-防止SQL注入式攻击

execute与executeUpdate的相同点:都可以执行增加,删除,修改

不同1:

execute可以执行查询语句,然后通过getResultSet,把结果集取出来

executeUpdate不能执行查询语句

 
不同2:


execute返回boolean类型,true表示执行的是查询语句,false表示执行的是insert,delete,update等等
executeUpdate返回的是int,表示有多少条数据受到了影响

DAO = Data   Access Object      数据访问对象

把数据库相关的操作都封装在这个类里面,其他地方看不到JDBC的代码

DAO接口

package Bean;

import java.util.List;


public interface DAO{
    //增加
    public void add(Hero hero);
    //修改
    public void update(Hero hero);
    //删除
    public void delete(int id);
    //获取
    public Hero get(int id);
    //查询
    public List<Hero> list();


}

    设计HeroDAO类,实现DAO接口,将一系列操作方法都封装在类里

package Bean;

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class HeroDAO implements DAO{

    public HeroDAO() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }//把驱动的初始化放在了构造方法HeroDAO里,因为驱动初始化只需要执行一次,所以放在这里更合适,其他方法里也不需要写了,代码更简洁

    public Connection getConnection() throws SQLException {

        return DriverManager.getConnection("jdbc:mysql://localhost:3306/base", "root","root");

    }//getConnection方法返回连接所有的数据库操作都需要事先拿到一个数据库连接Connection,以前的做法每个方法里都会写一个,如果要改动密码,那么每个地方都需要修改。 通过这种方式,只需要修改这一个地方就可以了。 代码变得更容易维护,而且也更加简洁。

    public int getTotal() {//返回表里多少条数据

        int total = 0;

        try  {
            Connection c =  getConnection();

            Statement s = c.createStatement();

            String sql = "select count(*) from hero";

            ResultSet rs = s.executeQuery(sql);

            while (rs.next()) {

                total = rs.getInt(1);
            }

            System.out.println("total:" + total);

        } catch (SQLException e) {

            e.printStackTrace();
        }
        return total;
    }


    public void add(Hero hero) {   //增加英雄

        String sql = "insert into hero values(?,?,?,?)";

        try  {
            Connection c = getConnection();

            PreparedStatement  ps = c.prepareStatement(sql);

            ps.setObject(1, hero.id);

            ps.setObject(2, hero.name);

            ps.setObject(3, hero.weight);

            ps.setObject(4, hero.age);

            ps.execute();


        } catch (SQLException e) {

            e.printStackTrace();
        }
    }



    public void update(Hero hero) {  //更新英雄

        String sql = "update hero set name = ?,weight=?,age=? where id = ?";

        try  {

            Connection c = getConnection();

            PreparedStatement  ps = c.prepareStatement(sql);

            ps.setObject(1, hero.name);

            ps.setObject(2, hero.weight);

            ps.setObject(3, hero.age);

            ps.setObject(4, hero.id);

            ps.execute();

        } catch (SQLException e) {

            e.printStackTrace();
        }

    }

    public void delete(int id) {  //删除序号为id 的英雄

        String sql = "delete from hero where id = ?";

        try {
            Connection c = getConnection();

            PreparedStatement st = c.prepareStatement(sql);

            st.setObject(1,id);

            st.execute();

        } catch (SQLException e) {

            e.printStackTrace();
        }
    }


    public Hero get(int id) {//得到序号为id的英雄数据

         Hero hero = null;

        try  {
            Connection c = getConnection();



            String sql = "select * from hero where id = ? ";

            PreparedStatement s = c.prepareStatement(sql);

            s.setObject(1,id);

            ResultSet rs = s.executeQuery();

            if (rs.next()) { // 因为id是唯一的,ResultSet最多只能有一条记录所以使用if代替while

                hero = new Hero();

                String name = rs.getString(2);

                float weight = rs.getFloat(3);

                int age = rs.getInt(4);

                hero.name = name;

                hero.weight = weight;

                hero.age = age;

                hero.id = id;

            }

        } catch (SQLException e) {

            e.printStackTrace();
        }
        return hero;
    }

    public List<Hero> list() {

        return list(0, Short.MAX_VALUE);

    }

    public List<Hero> list(int start, int count) {  //分页显示

        List<Hero> heros = new ArrayList<Hero>();

        String sql = "select * from hero order by id desc limit ?,? ";

        try {

            Connection c = getConnection();

            PreparedStatement ps = c.prepareStatement(sql);

            ps.setInt(1, start);

            ps.setInt(2, count);

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {

                Hero hero = new Hero();

                int id = rs.getInt(1);

                String name = rs.getString(2);

                float weight = rs.getFloat(3);

                int age = rs.getInt(4);

                hero.id = id;

                hero.name = name;

                hero.weight = weight;

                hero.age = age;

                heros.add(hero);
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return heros;
    }

}

Hero类

package Bean;

public class Hero {

    int id;

    public String name;

    public float weight;

    public int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getWeight() {
        return weight;
    }

    public void setWeight(float weight) {
        this.weight = weight;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 测试类

package Bean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class Test {

    public static void main(String[] args) {

        Hero h = new Hero();

        HeroDAO h1 = new HeroDAO();

     /*   h.setId(3);

         h.setName("asas");

         h.setWeight(50);

         h.setAge(20);

          h1.add(h);    增加方法  */

        h1.update(h);  // 更新方法


    /*    h.setId(3);

        h1.delete(h.id); //删除方法    */



      /*
        h.setId(3);

        h =  h1.get(h.id);       获取方法

        System.out.println(h.id);

        System.out.println(h.name);

        System.out.println(h.weight);

        System.out.println(h.age);     */


    /*  List<Hero> hero1 = new ArrayList<Hero>();   分页显示

        hero1 =  h1.list(0,5);

        for(int i = 0;i< hero1.size();i++){

      System.out.println(hero1.get(i).id+" "+hero1.get(i).name+" "+hero1.get(i).weight+" "+hero1.get(i).age);

        }     */

    }
}

发布了8 篇原创文章 · 获赞 0 · 访问量 127

猜你喜欢

转载自blog.csdn.net/cypherO_O/article/details/104401186
今日推荐