JDBC简单的增删改查

最近在学习mysql简单的增删改查,然后根据网上的一些教程通过jdbc对数据库进行了操作,现在把编写的一个类源码发出来,做学习交流。


package jdbc;

import java.sql.*;

public class MysqlDemo {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";

    static final String USER = "root";
    static final String PASS = "root123";

    public static void main(String[] args) {

        String sql = "select id,name,sex,age from students";
        String sql2 = "update students set age=age+3";
        MysqlDemo mysqlDemo = new MysqlDemo();
        mysqlDemo.getConn();
        try {
            mysqlDemo.select(sql);
            mysqlDemo.operateMysql(sql2);
            System.out.println();
            mysqlDemo.select(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        System.out.println("Goodbye");
    }

    public Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;

    }

    public void select(String sql) throws SQLException {
        Connection conn = getConn();
        Statement stmt = conn.createStatement()
        ResultSet result = stmt.executeQuery(sql);

        while (result.next()) {
            System.out.print("id: " + result.getInt("id"));
            System.out.print(" name: " + result.getString("name"));
            System.out.print(" sex: " + result.getString("sex"));
            System.out.println(" age: " + result.getInt("age"));
        }
        result.close();
        stmt.close();
        conn.close();
    }

    public void operateMysql(String sql) throws SQLException {
        Connection conn = getConn();
        Statement stmt = conn.createStatement();
        stmt.execute(sql);
        stmt.close();
        conn.close();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值