1、在Maven的pom.xml文件中引入MySql的驱动
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency>
2、idea(版本:2021.2.2)JDBC链接MySql数据库
3、编写JDBC代码 :
package com.hong.test; import java.sql.*; public class TestJDBC { public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/JDBC?useUnicode=true&characterEncoding=utf-8"; String user = "root"; String password = "root"; //加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); //创建数据库链接对象 Connection connection = DriverManager.getConnection(url, user, password); //插入数据的sql语句 String sql = "insert into admin(username, password, email, birthday) VALUES (?,?,?,?)"; //操作数据库 PreparedStatement PreparedStatement statement = connection.prepareStatement(sql); //插入数据 statement.setString(1,"李四"); statement.setString(2,"123456"); statement.setString(3,"ls@qq.com"); statement.setDate(4, new Date(new java.util.Date().getTime())); //i : 返回受影响的行数 int i = statement.executeUpdate(); if(i>0){ System.out.println("插入成功@"); }else{ System.err.println("插入失败@"); } } }