JDBC对数据库的简单操作

/**
     *  获取数据库连接
     */
    public Connection GetConnection(){
        Connection connection=null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            try {
                connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","orcl_test","orcl_test");
            } catch (SQLException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        return connection;
    }
    
    /**
     *  添加方法
     */
    
    public boolean Add(Student stu){
        Connection resConnection = GetConnection();   
        String insertDataSql=String.format("insert into student(sid, sname, sage, ssex) "
                + "values (sid_seq.nextval, %s, %s, %s)", 
                "?","?","?");
        try {
            PreparedStatement addStatement = resConnection.prepareStatement(insertDataSql);
            addStatement.setString(1, stu.getsName());
            addStatement.setInt(2, stu.getsAge());
            addStatement.setString(3, String.valueOf(stu.getsSex()));
            int addRes = addStatement.executeUpdate();
            addStatement.close();
            resConnection.close();
            if (addRes>=0) {
                return true;
            }
            else{
                return false;
            }
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        return false;
    }

jar包:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

 

posted @ 2016-10-26 15:47  洛晨随风  阅读(228)  评论(0编辑  收藏  举报