利用JDBC连接MySQL数据库

public static void main(String[] args){
        ResultSet rs=null;// 创建一个结果集对象
        PreparedStatement pre=null;// 创建预编译语句对象,一般都是用这个而不用Statement
        Connection conn=null;// 创建一个数据库连接
        try{
            Class.forName("com.mysql.jdbc.Driver");;// 加载MySQL驱动程序
            System.out.println("开始尝试连接数据库!");
            String URL="jdbc:mysql://localhost:3306/test";  // test是MySQL的默认数据库名
            String user="username";
            String password="password";
            //一个connection代表一个数据库连接
            conn=(Connection) DriverManager.getConnection(URL,user,password);// 获取连接    
            String sql="Select*from emp";
            //创建一个prepareStatement对象来蒋SQL语句发送到数据库
            pre=conn.prepareStatement(sql); // 实例化预编译语句 
            rs=pre.executeQuery();// 执行查询,注意括号中不需要再加参数
            System.out.print(pre+"\n");
            System.out.print(rs+"\n");
            //遍历
            while(rs.next()){
                System.out.print(rs.getString("name")+"\t");
                System.out.print(rs.getString("age")+"\n");
            }
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try{
            // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
            // 注意关闭的顺序,最后使用的最先关闭
                if(rs!=null){
                    rs.close();
                    rs=null;
                }
                if(pre!=null){
                    pre.close();
                    pre=null;
                }
                if(conn!=null){
                    conn.close();
                    conn=null;
                    System.out.println("数据库连接已关闭!");
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值