IDEA使用JDBC连接Mysql数据库
在项目中添加连接Mysql数据库的jar包
在项目中创建util包和DBUtil类用来存放数据库连接的java代码。
完整代码
package com.zsh.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class DBUtil {//创建数据库连接public static Connection getConn(){Connection conn = null;String url = "jdbc:mysql://localhost:3306/school"; //数据库名称schoolString user = "root"; //数据库登录用户名String pwd = "111"; //数据库登录密码try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection(url, user, pwd);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}//关闭数据库连接public static void closeConn(Connection conn, PreparedStatement ps, ResultSet rs){if(conn!=null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}