JDBC入门学习

本文介绍了使用JDBC进行数据库访问的基本步骤,包括加载驱动、连接数据库、创建Statement执行SQL、处理查询结果以及事务管理。作者分享了简单的插入和查询示例,适合Java初学者学习JDBC入门。
摘要由CSDN通过智能技术生成

简单说两句

作者:后端小知识

CSDN个人主页后端小知识

🔎GZH后端小知识

🎉欢迎关注🔎点赞👍收藏⭐️留言📝

image-20231006234204124

JDBC

内容和代码为在校期间做实验写的,初学者可以参考参考,其中也有很多写法不规范,但是入门还是可以,后面看情况可以出一篇详细的学习JDBC的文章

JDBC访问数据库步骤

• 1:加载一个Driver驱动

• 2:创建数据库连接(Connection)

• 3 :创建SQL命令发送器Statement

• 4:通过Statement发送SQL命令并得到结果

• 5:处理结果(select语句)

• 6:关闭数据库资源

• ResultSet

• Statement

• Connection

public class TestInsert {
    public static void main(String[] args) throws Exception{
        String driver = "com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://127.0.0.1:3306/shiyan?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        String user="root";
        String pasaword="tcx119";
        //加载驱动
        Class.forName (driver);
        //和数据库建立连接
        Connection conn = DriverManager.getConnection (url,user,pasaword);
       // System.out.println (conn);
        //创建sql命令发射器
        Statement smt = conn.createStatement ();
        //准备sql命令
        String sql = "insert into score values(12345666,'X6666',90.2,85.3)";
        //处理结果
        int n = smt.executeUpdate (sql);
        if(n>0){
            System.out.println ("插入成功");
        }else{
            System.out.println ("插入失败");
        }
        //关闭资源
        smt.close ();
        conn.close ();
    }
}

查询的结果

code

//这是Emp的代码
public class Emp {
    private String teacherno;
    private String tname;
    private String major;
    private String prof;
    private String department;

    public Emp() {
    }

    public Emp(String teacherno, String tname, String major, String prof, String department) {
        this.teacherno = teacherno;
        this.tname = tname;
        this.major = major;
        this.prof = prof;
        this.department = department;
    }

    public String getTeacherno() {
        return teacherno;
    }

    public void setTeacherno(String teacherno) {
        this.teacherno = teacherno;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getProf() {
        return prof;
    }

    public void setProf(String prof) {
        this.prof = prof;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "teacherno='" + teacherno + '\'' +
                ", tname='" + tname + '\'' +
                ", major='" + major + '\'' +
                ", prof='" + prof + '\'' +
                ", department='" + department + '\'' +
                '}';
    }
}
//这才是主场
public class TestSelect {
    public static void main(String[] args) throws SQLException {
        List<Emp> list = selectAll ();
        for (Emp emp:list){
            System.out.println (emp.getTeacherno ()+"\t"+emp.getTname ()+
                    "\t"+emp.getMajor ()+"\t"+emp.getProf ()+"\t"+emp.getDepartment ());
        }
    }
    //后台处理
    public static List<Emp> selectAll() throws SQLException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://127.0.0.1:3306/shiyan?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        String user="root";
        String password="tcx119";
        Connection conn=null;
        Statement stmt = null;
        ResultSet rs=null;
        Emp emp = null;
        List<Emp> list =new ArrayList<Emp>();
        try{
            Class.forName (driver);
            conn = DriverManager.getConnection (url,user,password);
            stmt= conn.createStatement ();
            String sql = " select * from teacher";
            rs= stmt.executeQuery (sql);
            while(rs.next ()){
                String teacherno = rs.getString ("teacherno");
                String tname = rs.getString ("tname");
                String major = rs.getString ("major");
                String prof = rs.getString ("prof");
                String department = rs.getString ("department");
                emp=new Emp (teacherno,tname,major,prof,department);
                list.add (emp);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace ();
        } finally {
            assert rs != null;
            rs.close ();
            stmt.close ();
            conn.close ();
        }
        return list;
    }
}

模拟登录

public class Login {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        //前台
        Scanner sc = new Scanner (System.in);
        System.out.println ("请输入用户名");
        String userId = sc.next ();
        System.out.println ("请输入密码");
        String inputPassword = sc.next ();
        User user = testLogin (userId,inputPassword);
        if (user==null){
            System.out.println ("登录失败,请检查用户名或密码是否正确");
        }else{
            System.out.println ("登录成功: 姓名: "+user.getRealName ());
        }

    }
//    后台
    public static User testLogin(String userId,String inputPassword) throws ClassNotFoundException, SQLException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://127.0.0.1:3306/shiyan?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        String user="root";
        String pasaword="tcx119";
        Class.forName (driver);
        User user2=null;
        Connection conn = DriverManager.getConnection (url,user,pasaword);
        String sql = "select * from t_user where userid = ? and password = ? ";

//        Statement stmt = conn.createStatement ();
        PreparedStatement pstmt = conn.prepareStatement (sql);
        pstmt.setString (1,userId);
        pstmt.setString (2,inputPassword);
        ResultSet rs =  pstmt.executeQuery ();
        if(rs.next ()){
            String realName=rs.getString ("realname");
            double money = rs.getDouble ("money");
            user2 = new User (userId,realName,inputPassword,money);
            return user2;
        }
        return user2;
    }
}

事务

public class TestTransation {
    public static void main(String[] args)  {
        Connection conn=null;
        try{
            String driver = "com.mysql.cj.jdbc.Driver";
            String url="jdbc:mysql://127.0.0.1:3306/shiyan?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
            String user="root";
            String pasaword="tcx119";
            Class.forName (driver);
            conn = DriverManager.getConnection (url,user,pasaword);
            Statement stmt = conn.createStatement ();
            conn.setAutoCommit (false);
            stmt.executeUpdate ("update t_user set money = money-2000 where userid = 'lisi' ");
            stmt.executeUpdate ("update t_user set money = money+2000 where userid = 'zhangsan' ");
            conn.commit ();
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        } catch (SQLException e) {
            //手动的回滚事务,回到所有DML操作执行之前的状态
            try {
                assert conn != null;
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            e.printStackTrace ();
        }
        
    }
}

【都看到这了,点点赞点点关注呗,爱你们】😚😚

抽象工厂  引导关注

结语

谢谢你的阅读,由于作者水平有限,难免有不足之处,若读者发现问题,还请批评,在留言区留言或者私信告知,我一定会尽快修改的。若各位大佬有什么好的解法,或者有意义的解法都可以在评论区展示额,万分谢谢。
写作不易,望各位老板点点赞,加个关注!😘😘😘

💬

作者:后端小知识

CSDN个人主页后端小知识

🔎GZH后端小知识

🎉欢迎关注🔎点赞👍收藏⭐️留言📝

评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不正经小新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值