JDBC连接Mysql数据库

2023-12-22 19:03:56

JDBC连接数据库

import java.sql.*;

public class Test01 {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;

        ResultSet rs=null;

        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接对象
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3307/j3071test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8","root","root");
            //3.创建语句查询
            statement=connection.createStatement();
//            //4.执行语句并且返回结果
//            String sql="select * from student where age=22";
//            rs= statement.executeQuery(sql);
//            //5.遍历结果集
//            while(rs.next()){
//                //获取需要的字段
//                String name = rs.getString("name");
//                int id = rs.getInt("id");
//                System.out.println("id:"+id+",Name:"+name);
//            }

//          修改语句
            String sql="insert into student (id,name,age,sex) values(id,'j3071',20,'男')";
            //字符串拼接
            String str1="insert into student (id,name,age,sex) values(id,";
            String name="张三";
            int age=20;
            String sql1=str1+"'"+name+"',"+age+","+"'男')";
            int row = statement.executeUpdate(sql);//返回值是影响的行数
            //增删改的语句都用executeUpdate
            System.out.println("受影响的行数为:"+row);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                if (rs!=null){
                    rs.close();
                }
                if (statement!=null){
                    statement.close();
                }
                if (connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

文章来源:https://blog.csdn.net/m0_69005620/article/details/135153907
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。