java,android连接数据库mysql

来源:互联网 发布:nginx 维护页面配置 编辑:程序博客网 时间:2024/05/29 18:56
//声明Connection对象Connection con;//驱动程序名String driver = "com.mysql.jdbc.Driver";//URL指向要访问的数据库名mydataString url = "jdbc:mysql://localhost:3306/data";//MySQL配置时的用户名String user = "root";//MySQL配置时的密码String password = "root";//遍历查询结果集try {    //加载驱动程序    Class.forName(driver);    //1.getConnection()方法,连接MySQL数据库!!    con = DriverManager.getConnection(url,user,password);    if(!con.isClosed())        System.out.println("Succeeded connecting to the Database!");    //2.创建statement类对象,用来执行SQL语句!!    Statement statement = con.createStatement();    //要执行的SQL语句    String sql = "select * from student";    //3.ResultSet类,用来存放获取的结果集!!    ResultSet rs = statement.executeQuery(sql);                 String name = null;    String id = null;    while(rs.next()){        //获取stuname这列数据        name = rs.getString("name");        //获取stuid这列数据        id = rs.getString("id");    }    rs.close();    con.close();} catch(ClassNotFoundException e) {       //数据库驱动类异常处理    System.out.println("Sorry,can`t find the Driver!");       e.printStackTrace();       } catch(SQLException e) {    //数据库连接失败异常处理    e.printStackTrace();      }catch (Exception e) {    e.printStackTrace();}finally{    System.out.println("数据库数据成功获取!!");}
0 0
原创粉丝点击