Intellij IDEA 连接数据库(MySQL)详细过程
1.使用IDEA自带的Database模块就可以连接到数据库
2.选择数据库MYSQL并且连接到数据库
3.可以查看数据库和表,以及进行增删改等操作
4.导入驱动
配置pom.xml 导入mysql-connector-java:5.1.49
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> </dependencies>
5.使用JDBC操作数据库
package com.qzxiaofeng.jdbc; import java.sql.*; /** * @author 刘晓峰 */ public class FirstJdbc1 { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/xiao?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"; PreparedStatement statement = null; ResultSet resultSet = null; Connection connection=null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection(url,"root","123456"); statement = connection.prepareStatement("select * from t_manager"); resultSet = statement.executeQuery(); while (resultSet.next()){ System.out.println("id:"+resultSet.getInt("id")); System.out.println("username:"+resultSet.getString("username")); System.out.println("password:"+resultSet.getString("password")); } } catch (Exception e) { e.printStackTrace(); } finally { if(null!=resultSet){ try { resultSet.close(); } catch (SQLException exception) { exception.printStackTrace(); } } if(null!=statement){ try { statement.close(); } catch (SQLException exception) { exception.printStackTrace(); } } if(null!=connection){ try { connection.close(); } catch (SQLException exception) { exception.printStackTrace(); } } } } }
6.程序执行结果,执行了一条查询语句
完结,加油!