Java:jdbc

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";

        String username = "root";
        String password = "1340508016";
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.创建一个数据库对象,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送SQL的对象Statement
        Statement statement = connection.createStatement();
        //4.编写SQL语句
        String sql = "select * from users";
        //5.执行SQL语句,返回一个ResultSet结果集
        ResultSet rs = statement.executeQuery(sql);

        //6.遍历
        while (rs.next()){
            System.out.println("id"+rs.getObject("id"));
            System.out.println("name"+rs.getObject("name"));
            System.out.println("password"+rs.getObject("password"));
            System.out.println("email"+rs.getObject("email"));
            System.out.println("birthday"+rs.getObject("birthday"));

        }
        //7.关闭连接,释放资源
        connection.close();
        statement.close();
        rs.close();
    }
}
PreparedStatement:
public class TestJdbc02 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";

        String username = "root";
        String password = "1340508016";

        Class.forName("com.mysql.jdbc.Driver");

        Connection connection = DriverManager.getConnection(url, username, password);

        String sql = "insert into users(id, name, password, email, birthday) VALUES (?,?,?,?,?)";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,4);
        preparedStatement.setString(2,"老六");
        preparedStatement.setString(3,"123456");
        preparedStatement.setString(4,"ll@qq.com");
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));

        //受影响的行数
        int i = preparedStatement.executeUpdate();

       if (i>0){
           System.out.println("插入成功");
       }

        preparedStatement.close();
        connection.close();



    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值