[Java连接MySQL数据库——含详细步骤和代码](https://www.cnblogs.com/town123/p/8336244.html)

本章节我们为大家介绍 Java 如何使用 使用 JDBC 连接 MySQL 数据库。

Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到 jar 库文件,然后在对应的项目中导入该库文件。

img

你可以下载我提供的 jar 包:mysql-connector-java-5.1.39-bin.jar

本实例使用的是 Eclipse,导入 jar 包:

img

MySQL 8.0 以上版本的数据库连接有所不同:

  • 1、MySQL 8.0 以上版本驱动包版本 mysql-connector-java-8.0.16.jar
  • 2、com.mysql.jdbc.Driver 更换为 com.mysql.cj.jdbc.Driver
  • MySQL 8.0 以上版本不需要建立 SSL 连接的,需要显示关闭。
  • allowPublicKeyRetrieval=true 允许客户端从服务器获取公钥。
  • 最后还需要设置 CST。

加载驱动与连接数据库方式如下:

Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");

这是解压后的文件:

img

1、新建java项目 然后新建一个文件夹——libs(用来放各种外部包)

img

右键工程名(我的是Mysql)—新建New—文件夹Folder—Folder name为libs—Finish。

2、在包里面加入连接mysql数据库的包

即刚才解压后得到的 mysql-connector-java-5.1.45-bin.jar

然后复制粘贴到我们java项目的libs文件夹下面(注意是物理地址里);

此时,在eclipse中—右击libs文件夹—刷新Refresh,就将下载好的JDBC放到该文件夹下,如下图所示:

img

3、构建路径上的jar包

在eclipse中

a:点击项目Project——选择属性Propeties

img

b:进行添加

打开属性Propeties后,点击java构建路径(Java Build Path)

点击添加jar(Add JARs...),选择你的项目下的jar包,然后确定,最后添加完成

img

img

4.查询代码

package Operation;
import java.sql.*;

public class Select {

// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String DB_URL = "jdbc:mysql://localhost:3306/xyp";
 
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
//static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";



// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "123456";
 
public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    try{
        // 注册 JDBC 驱动
        Class.forName(JDBC_DRIVER);
    
        // 打开链接
        System.out.println("连接数据库...");
        conn = DriverManager.getConnection(DB_URL,USER,PASS);
    
        // 执行查询
        System.out.println(" 实例化Statement对象...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT  Sname, Sno FROM student";
        ResultSet rs = stmt.executeQuery(sql);
        
        // 展开结果集数据库
        System.out.println("--------------------------------");
        System.out.println("学号"+"		"+"姓名"+"	");
        System.out.println("--------------------------------");
        while(rs.next()){
            // 通过字段检索
           
            String name = rs.getString("Sname");
            String sno = rs.getString("Sno");

            // 输出数据
            System.out.println(sno+"	"+name+"	");
            
			/*
			 * System.out.print(" 姓名: " + name+""); System.out.print("学号: " + sno);
			 */
            System.out.print("
");
        }
        
        // 完成后关闭
        rs.close();
        stmt.close();
        conn.close();
    }catch(SQLException se){
        // 处理 JDBC 错误
        se.printStackTrace();
    }catch(Exception e){
        // 处理 Class.forName 错误
        e.printStackTrace();
    }finally{
        // 关闭资源
        try{
            if(stmt!=null) stmt.close();
        }catch(SQLException se2){
        }// 什么都不做
        try{
            if(conn!=null) conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

}

结果如下:

5.插入代码

package Operation;
import java.sql.*;
public class Insert {//插入操作
	  public static void main(String args[])
	   {
	    try
	      { 
	    	Class.forName("com.mysql.jdbc.Driver"); //启动驱动
	    	System.out.println("数据库启动成功");
	      }
	    catch (ClassNotFoundException ce)
	      { 
	    	System.out.println("SQLException:"+ce.getMessage()); 
	      }
	      

	    try {
	        java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","123456");//连接数据库  数据库名 密码 用户名
	        Statement stmt = con.createStatement();
	        String sqlstr = "insert into Student values('2001131', '谢应鹏',' 男',21,'CS','2021-6-24')";
	        stmt.executeUpdate(sqlstr);
	        System.out.println("插入成功");
	        //stmt.executeUpdate("insert into employee values('2020','翟建设','男',746)");
	        stmt.close();      
	        con.close();  //关闭连接
	      }
	    catch (SQLException e)
	      { System.out.println("SQLException:"+e.getMessage()); }
	   }   

 }  

结果如下:

6.删除代码

package Operation;
import java.sql.*;
class Delete{//删除操作
	public static void main(String args[]){
		try{ 
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("数据库启动成功");
		}
		catch (ClassNotFoundException ce){
			System.out.println("SQLException:"+ce.getMessage());
		}
		try {
			java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","123456");
			Statement stmt = con.createStatement();
			String   sql = "delete from p where Pno='p1'";
			String sql1 = "SET FOREIGN_KEY_CHECKS = 1";
			stmt.executeUpdate(sql1);//解决办法二:不检查外链,设置FOREIGN_KEY_CHECKS变量:
			/*

   * SET FOREIGN_KEY_CHECKS = 0; DELETE FROM `goods` WHERE `goods_id` = '11'
	   * 删除完成后设置 SET FOREIGN_KEY_CHECKS = 1;
			 */
			stmt.executeUpdate(sql);
			System.out.println("删除成功");
			stmt.close();
			con.close();
		}
		catch (SQLException e){
			System.out.println("SQLException:"+e.getMessage()); 
		}

	}  

} 

结果如下:

7.更新代码

package Operation;
import java.sql.*;
class Update{//更新操作
	public static void main(String args[]) {
		try
			{ 
				Class.forName("com.mysql.jdbc.Driver");
				System.out.println("数据库启动成功");
			}
		catch (ClassNotFoundException ce){
			System.out.println("SQLException:"+ce.getMessage());
		}
		try{
			java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","xyp166166");
			Statement stmt = con.createStatement();
			String   sql = "update student set Sage= '31'" + "where Sname= '王敏'";
			stmt.executeUpdate(sql);
			System.out.println("插入成功");
			stmt.close();     
			con.close();    
		}
		catch (SQLException e){
			System.out.println("SQLException:"+e.getMessage());
		}
    

	} 

} 

结果如下:

8、连接mysql数据库失败原因分析:

1、数据库的服务是否打开

2、是否在新建了对应的数据库

3、是否添加了jar包

4、是否加载了驱动

5、连接字符串、登录名以及密码是否有误

9.联系方式

qq:2061302791

微信:xie2061302791

电话:15284524485

个人网站:https://xieyingpeng.github.io/

Github:https://github.com/xieyingpeng/

博客园:https://www.cnblogs.com/Xieyingpengz

知乎:https://www.zhihu.com/people/nan-qiao-12-73

gitee:https://gitee.com/xie-yingpeng/project-1.git

bilibili:https://space.bilibili.com/617198338?share_medium=android&share_source=copy_link&bbid=XY2BDF522C748A159BE7DD354D6DFFB963728&ts=1612520115798

原文地址:https://www.cnblogs.com/Xieyingpeng/p/14923815.html