JDBC连接Mysql数据库

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();
            }
        }
    }
}

你可能感兴趣的:(Mysql,Java面试,数据库,mysql,java)