To connect to the mysql database, first we need to import the database driver jar package into the project, then create a Jdbc tool class, then write a method to obtain the database connection, and finally Determine whether the obtained Connection value is empty. If it is not empty, it means the connection has been successful.
Next let’s take a look at the specific code:
(Video tutorial recommendation: java video)
Jdbc tool class
package com.zwork.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JdbcUtil { private static final String USER = "root";//用户 private static final String PASSWORD = "root";//密码 static final String DRIVER="com.mysql.jdbc.Driver";//数据库驱动 static final String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";//数据库地址 private static Connection conn; //加载数据库驱动 static{ try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //获取连接的方法 public static Connection getConnection(){ try { return conn = DriverManager.getConnection(URL,USER,PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return null; } }
Test code:
package com.zwork.test; import com.zwork.utils.JdbcUtil; import java.sql.Connection; public class JdbcUtilTest { public static void main(String[] args) { Connection conn = JdbcUtil.getConnection(); System.out.println(conn); } }
Running results:
com.mysql.jdbc.Connection@5f8ed237
Recommended tutorial: java entry program
The above is the detailed content of How to connect to mysql database in java. For more information, please follow other related articles on the PHP Chinese website!