java基础——jdbc基本操作

package jsbc;

import java.sql.*;

public class TestJDBC {
    public static void main(String[] args) {

        Connection c = null;
        Statement s = null;
        try {
            //初始化驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("数据可加载成功!!!");

            //建立数据库连接
            c  = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306" +
                    "/how2java?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC","root","123");
            System.out.println("连接成功,获取对象:"+c);

            //创建Statement语句
            s  = c.createStatement();

            //增加
            //String sql = "insert into hero values (null,"+"'提莫'"+","+313.0f+","+50+")";
            /*for(int i=0;i<5;i++){
                String sqlStr = "insert into hero values(null,"+"'hero"+i+"'"+","+313.0f+","+50+")";
                s.execute(sqlStr);
            }*/
            //删除
            //String sql = "delete from hero where id=5";
            //修改
            //String sql = "update hero set name = 'new name' where id = 3";
            //s.execute(sql);
            //查询
            String sql = "select * from hero";
            ResultSet rs = s.executeQuery(sql);
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString(2);
                float hp = rs.getFloat("hp");
                int damage = rs.getInt(4);
                System.out.printf("%d\t%s\t%f\t%d%n",id,name,hp,damage);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            if(s!=null){
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(c!=null){
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值