21xrx.com
2025-07-10 02:47:19 Thursday
文章检索 我的文章 写文章
MySql的连接方式及案例
2023-06-15 19:54:22 深夜i     11     0
Java MySQL JDBC驱动程序

Java和MySQL是两个非常常用的工具,在实际工作中我们常常需要将Java和MySQL进行连接,这个连接方式非常的重要。下面我们来看看Java和MySQL的连接方式以及案例。

Java和MySQL的连接方式有许多种,大致分为三类:JDBC驱动程序,连接池和ORM框架。其中,JDBC驱动程序是最基础的连接方式,连接池和ORM框架则是在此基础上进行封装和优化。

下面我们就来看一个使用JDBC驱动程序的连接方式的案例:

public class JDBCExample {
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost:3306/EMP";
  static final String USER = "username";
  static final String PASS = "password";
 
  public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
     Class.forName("com.mysql.jdbc.Driver");
     System.out.println("连接数据库...");
     conn = DriverManager.getConnection(DB_URL,USER,PASS);
     System.out.println("实例化Statement对象...");
     stmt = conn.createStatement();
     String sql;
     sql = "SELECT id, name, age FROM Employees";
     ResultSet rs = stmt.executeQuery(sql);
     while(rs.next()){
      int id = rs.getInt("id");
      int age = rs.getInt("age");
      String name = rs.getString("name");
      System.out.print("ID: " + id);
      System.out.print(", 名字: " + name);
      System.out.print(", 年龄: " + age);
      System.out.println();
     }
     rs.close();
     stmt.close();
     conn.close();
   }catch(SQLException se){
     se.printStackTrace();
   }catch(Exception e){
     e.printStackTrace();
   }finally{
     try{
      if(stmt!=null) stmt.close();
     }catch(SQLException se2)
    
     try{
      if(conn!=null) conn.close();
     }catch(SQLException se){
      se.printStackTrace();
     }
   }
   System.out.println("Goodbye!");
  }
}

以上就是一个使用JDBC驱动程序连接MySQL的案例。在这个案例中,我们首先通过Class.forName()来加载MySQL的JDBC驱动程序,然后通过DriverManager.getConnection()方法来获取数据库连接。最后,我们通过Statement对象来执行SQL语句,并通过ResultSet读取查询结果。

  
  

评论区