JDBC的连接代码

写代码的步骤:
/* 首先要启动数据库,而且数据库中的下标都是从1开始的
* 1.加载数据库的JDBC驱动
* 2.创建连接
* 3.创建命令
* 4.准备sql语句
* 5.执行sql
* 6.处理结果
* 7.关闭结果
* 8.关闭命令
* 9.关闭连接
* */

public class JdbcCase1 {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //JDBC URL协议
            //jdbc:<datdbaseType>://host:port/<databaseName>?user=xxx&password=xxx
            //jdbc:mysql://127.0.0.1:3306/memo?user=root&password=daixueting52o99

            //2.创建连接
            String url="jdbc:mysql://127.0.0.1:3306/memo?user=root&password=daixueting52o99";
            connection= DriverManager.getConnection(url);

            //3.创建命令
             statement=connection.createStatement();
            //4.准备sql语句  避险*的存在
            String sql="select id,name,created_time,modify_time from memo_group";
            //5.执行语句
            resultSet=statement.executeQuery(sql);
            //6.处理数据

            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                Timestamp created_time=resultSet.getTimestamp("created_time");
                Timestamp modify_time=resultSet.getTimestamp("modify_time");
                System.out.println(id);
                System.out.println(name);
                System.out.println(created_time);
                System.out.println(modify_time);

            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (resultSet!=null){
                //7.关闭结果
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
           if (statement!=null){
               //8.关闭命令
               try {
                   statement.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
           if (connection!=null){
               //9.关闭连接
               try {
                   connection.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值