JDBC - 基础操作

JDBC的概念

所谓的JDBC(Java Database Connectivity),就是java与数据库之间进行操作的一些API。毕竟数据库繁多,自然就需要将对数据库的操作封装起来,从而达到方便操作的目的。而一些优秀的orm框架的底层也是用JDBC实现的

常用接口

在JDBC当中有几个常用的API,分别是Statement,ResultSet,PreparedStatement。其中,Statement和PreparedStatement接口都是用于数据库的增删减查操作的,但是,PreparedStatement接口的效率会比Statement的效率要高,而且还极大程度的提高了安全性。

具体操作

接下来就让我们看看一些具体的操作吧(以MySQL为例子)。
首先,我先定义了一个和数据库储存值类型相匹配的类,用于方便对数据库的操作

public class InvoiceBean {
    String nameString;
    float unitPrice;
    int unit;
    float subtotal;
    
    public InvoiceBean(String name,int unit,float unitPrice,float subtotal) {
        // TODO Auto-generated constructor stub
        
        this.nameString = name;
        this.unit = unit;
        this.unitPrice = unitPrice;
        this.subtotal = subtotal;
        
    }
    
    public void setNameString(String nameString) {
        this.nameString = nameString;
    }
    
    public void setSubtotal(float subtotal) {
        this.subtotal = subtotal;
    }
    
    public void setUnit(int unit) {
        this.unit = unit;
    }
    
    public void setUnitPrice(float unitPrice) {
        this.unitPrice = unitPrice;
    }
    
    public String getNameString() {
        return nameString;
    }
    
    public float getSubtotal() {
        return subtotal;
    }
    
    public int getUnit() {
        return unit;
    }
    
    public float getUnitPrice() {
        return unitPrice;
    }
}

这是一个发票类,包含了物品的名字,物品的价格,数量,以及总价。
然后就是对数据库的一些操作。
首先就是连接数据库了

private static Connection getConnection(){
        
        //连接本地数据库的url语句(我的数据库名字叫invoice,因此是/invoice)
        String URL = "jdbc:mysql://localhost:3306/invoice";
        String USER = "root";
        String PASSWORD = "12345";
        
         Connection connection = null;
         
         try {
            //加载数据库
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            connection = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            PrintUtil.print("Load DB Failed");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            PrintUtil.print("Set Connection Failed");
        }
         
         return connection;
    }

之后就是利用SQL语句以及JDBC的接口对数据库进行一些增删减查的操作了。由于我定义的数据库的名字叫做InvoiceMessage,因此,SQL语句当中自然都有 from InvoiceMessage,update InvoiceMessage等等的语句

/**
     * 插入信息
     * @param invoice 发票信息
     * @return 0 SQL语句错误
     *         x 更新的条数
     */
    public static int insert(InvoiceBean invoice){
        
        int status = 0;
        
        String sqlString = "insert into InvoiceMessage (name,unit,unitPrice,subtotal) "
                + "values(?,?,?,?)";
        
        Connection connection = getConnection();
        PreparedStatement statement = null;
        
        try {
            statement = connection.prepareStatement(sqlString);
            
            //这个statement.setXX(int,XX);当中,第一个参数所对应的int 值指
            // 的是Sql语句当中的第几个?
            statement.setString(1, invoice.getNameString());
            statement.setInt(2, invoice.getUnit());
            statement.setFloat(3, invoice.getUnitPrice());
            statement.setFloat(4, invoice.getSubtotal());
            
            status = statement.executeUpdate();
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                connection.close();
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }
        
        return status;
    }
    
    /**
     * 更新信息
     * 
     * @param invoice
     * @return 0 SQL语句错误
     *         x 更新的条数
     *    
     */
    public static int update(InvoiceBean invoice){
        int status = 0;
        
        Connection connection = getConnection();
        PreparedStatement preparedStatement =  null;
        
        String sqlString = "update InvoiceMessage set unit=?,unitPrice=?,subtotal=? "
                + "where name=?";
        
        try {
            preparedStatement = connection.prepareStatement(sqlString);     
            
            preparedStatement.setInt(1, invoice.getUnit());
            preparedStatement.setFloat(2, invoice.getUnitPrice());
            preparedStatement.setFloat(3, invoice.getSubtotal());
            preparedStatement.setString(4, invoice.getNameString());
                        
            status = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                connection.close();
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        return status;
    }
    
    /**
     * 
     * 删除数据
     * @param invoice  要删除的发票的信息
     * @return 0 SQL语句错误
     *         x 进行操作的条数
     */
    public static int delete(InvoiceBean invoice){
        int status = 0;
        String sqlString = "delete from InvoiceMessage where name ='" + 
        invoice.getNameString() + "'";
        
        PreparedStatement preparedStatement = null;
        Connection connection = getConnection();
        
        try {
            preparedStatement = connection.prepareStatement(sqlString);
            
            status = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                connection.close();
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }   
        return status;
    }

    //获取数据库内所有的数据,以String的形式返回
    public static String getAll(){
        
        StringBuffer stringBuffer = new StringBuffer();
        
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        
        String sqlString = "select * from InvoiceMessage";
        
        
        try {
            preparedStatement = connection.prepareStatement(sqlString);
            
            ResultSet set = preparedStatement.executeQuery();
            
            int col = set.getMetaData().getColumnCount();
            
            while (set.next()) {
                for(int i = 1 ; i <= col ; i++){
                    //PrintUtil.print(set.getString(i) + "\t");
                    stringBuffer.append(set.getString(i) + " ");
                }
                stringBuffer.append("\n");
            }
            
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                connection.close();
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
                
        return stringBuffer.toString();
    }

当然,在进行这些操作之前,不要忘记先在控制台打开MySQL服务,而在完成任务之后也不要忘了关闭哦(这个操作是需要管理员权限的)

你可能感兴趣的:(JDBC - 基础操作)