利用JDBC连接MySQL数据库

来源:互联网 发布:sql建立数据库用户 编辑:程序博客网 时间:2024/05/01 09:42
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
原创粉丝点击