MYSQL和JAVA(课堂笔记)

时间:2022-01-12 19:04:23

MYSQL  数据库管理工具

JAVA    编程语言

数据库驱动(JAVA和MYSQL对接方式)

到官网上下载驱动    加载驱动

 

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

public class Sql{
  public static void main(String[] args){
    try{
      //加载驱动  加载到JVM中
      Class.forName("com.mysql.jdbc.Driver");
      //getConnection()方法,链接到mysql数据库
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名","用户名","密码");
      //验证链接是否成功
      if(!con.isClosed())
      System.out.println("Succeeded connecting to the Databases");
      //创建statement对象,用来执行sql语句
      Statement sta = con.createStatement();
      //要执行的sql语句
      String sql = "select * from student";
      //ResultSet类 存放获取的结果集
      ResultSet rs = sta.executeQuery(sql);
      while(rs.next()){
        String name = rs.getString("sname");
        int id = rs.getInt("id");
        System.out.println(name+"\t"+id);
      }
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}