package sqldemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class main {

    public static void main(String[] args) {
        //声明Connection对象
        Connection con;
        //驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名mydata
        String url = "jdbc:mysql://localhost:3306/student";
        //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("数据连接成功!");
            //2.创建dosql类对象,用来执行SQL语句!!
            Statement dosql = con.createStatement();
            //要执行的SQL语句
            String sql = "select * from STU";
            //3.ResultSet类,用来存放获取的结果集!!
            ResultSet rs = dosql.executeQuery(sql);
            System.out.println("-----------------");
            System.out.println("执行结果如下所示:");  
            System.out.println("-------------------------------------------");  
            System.out.println("序号"+"\t姓名" +"\t学号"+"\t手机号码");  
            System.out.println("-------------------------------------------");  
            String id = null;
            String name = null;
            String stunum = null;
            String phonenum = null;
            while(rs.next()){
            	//获取ID
            	id=rs.getString("id");
            	//获取学生姓名
                name = rs.getString("name");
                //获取学号
                stunum = rs.getString("StuNum");
                //获取手机号码
                phonenum=rs.getString("PhoneNum");
                //输出结果
                System.out.println(id+"\t"+name + "\t" + stunum+"\t"+phonenum);
            }
            rs.close();
            con.close();
        } catch(ClassNotFoundException e) {   
            //数据库驱动类异常处理
            System.out.println("找不到驱动程序!");   
            e.printStackTrace();   
            } catch(SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();  
            }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally{
        	
            //System.out.println("数据库数据成功获取!!");
        }
        
    }

}

 

 

版权声明:本文为soulsjie原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/soulsjie/p/7522862.html