数据库的连接

// Java连接数据库

Connection conn = null;
PreparedStatement stat = null;
Result result = null;
// 如果是Oracle数据库,则是 driver = "oracle.jdbc.OracleDriver";
private String driver = "com.mysql.jdbc.Driver";
// Oracle数据库: url = "jdbc:oracle:thin:@localhost:1521:数据库名";
private String url = "jdbc:mysql://localhost:3306/数据库名";
private  String username = "root";
private String password = "root";

/**
 * 获取Connection对象
 * @return 
 */
public Connection initConnection(){ 
    try{
        Class.forName(driver);
        conn = DriverManager.getConnection(url,username,password);
        System.out.println("连接数据库成功");
    } catch(ClassNotFoundException e){
        throw new RuntimeException("Class not found " + e);
    } catch(SQLException e){
        throw new RuntimeException("Connection Error! " + e);
    }
    return conn;
}

/**
 *
 */
    public void  UpdateData(String stuName, int gender, int age, String address) {
        conn = initConnection();
        String sql = "select id from student where 1 = 1 and stu_name = ?";
        String sqlStr = "update student set stu_name=?,gender=?,age=?,address=? where id=?";
        int count = 0;

        try {
            // 计算数据库student表中数据总数
            stat= connection.prepareStatement(sql);
            stat.setString(1, stuName);
            rs = stat.executeQuery();
            while (rs.next()) {
                count = rs.getInt(1);
                System.out.println(rs.getInt(1));
            }
            // 执行插入数据操作
            stat = connection.prepareStatement(sqlStr);
            stat.setString(1, stuName);
            stat.setInt(2, gender);
            stat.setInt(3, age);
            stat.setString(4, address);
            stat.setInt(5, count);
            stat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ReleaseResource();
        }
    }

    /**
     * 释放资源
     */
    public void ReleaseResource() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值