JAVA 使用JDBC连接Mysql数据库 (基础)

  1. 添加 maven 依赖
       <!--JDBC 数据库连接-->
       <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>5.1.40</version>
       </dependency>
    
  2. 编写java代码连接并查询数据
    import org.junit.Test;
    import java.sql.*;
    
    /**
      * Created by chengh on 2018/12/1.
      * 使用 JDBC连接数据库
      */
    public class JDBCCTest {
      @Test
      public void test(){
         String driver = "com.mysql.jdbc.Driver"; //驱动
         String url = "jdbc:mysql://localhost:3306/数据库名称"; 
         String userName = "root"; //mysql账号
         String password = "123456"; //密码
    
         Connection connection = null;
         Statement statement = null;
         ResultSet resultSet = null;
         try {
             //加载驱动程序
             Class.forName(driver);
    
             //连接数据库
             connection = DriverManager.getConnection(url, userName, password);
    
             statement = connection.createStatement();
    
             //结果集(通过查询语句查询后返回)
             resultSet = statement.executeQuery("SELECT * FROM student");
    
             while (resultSet.next()){
                 System.out.println(resultSet.getInt("id"));
                 System.out.println(resultSet.getString("name"));
             }
         } catch (ClassNotFoundException e) {
             System.out.println("加载驱动异常");
             e.printStackTrace();
         } catch (SQLException e) {
             System.out.println("数据库链接异常");
             e.printStackTrace();
         }finally {
    
         }
      }
    }
    

你可能感兴趣的:(java)