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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值