java中jdbc连接数据库操作

首先需要创建一个数据库,我们下载MySQL安装好之后打开,先用show databases查看本地数据库,一般都是有本地的数据,我们不用管,直接创建一个新的数据库,create databases <数据库名>,然后可以编辑刚刚创建的数据库了,use <数据库名>, 这样就创建了一个数据库。我们也可以用Navicat for MySQL来创建数据库。
import java.sql.*;

public class test {
    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 = "*********";
        //遍历查询结果集
        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 studinfo";
            String sql1 = "select * from grade";
            //3.ResultSet类,用来存放获取的结果集!!
            ResultSet rs = statement.executeQuery(sql);
            System.out.println("--------------------------------");
            System.out.println("执行结果如下所示:");  
            System.out.println("--------------------------------");  
            System.out.println("|   姓名        |" + " 性别    |" + "   年龄      |"+"chinese|"+"math|"+"english");  
            System.out.println("--------------------------------");  
            
            
            while(rs.next()){
                //获取stuname这列数据
//             rs.getInt(1);
             System.out.println(rs.getString(1)+"   "+rs.getString(2)+"      "+rs.getString(3));
             rs.getString(1);
//               System.out.println(rs);
                //获取stuid这列数据
       
            }
         
            rs.close();
            con.close();
            
            
 /*           while(rs.next()){
                //获取studinfo这列数据
             String studinfo = rs.getString("studinfo");
                //获取grade这列数据
             String grade = rs.getString("grade");
                //输出结果
                System.out.println(studinfo + "\t" + grade);
            }
*/
        } catch(ClassNotFoundException e) {   
            //数据库驱动类异常处理
            System.out.println("Sorry,can`t find the Driver!");   
            e.printStackTrace();   
            } catch(SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();  
            }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            System.out.println("数据库数据成功获取!!");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39478237/article/details/78359913