Java怎么连接MySQL。
1、首先当然需要新建一个Java Project项目,在新建好的Java Project项目中新建package,最后在package中新建一个Java项目。

2、右键你新建好的Java Project项目,选择new,然后选择Folder,如果选择new时候没有这个Folder这个选项,选择Other,然后搜索Folder,之后便能找到,这个Folder名字取为lib。建好之后如图所示。

3、连接MySQL,最重要的就是这边需要一个架包。我这边提供一个https://pan.baidu.com/s/1tc7Mz62CkLgRMcqcGTIjjw 密码:s30m。你也可以直接百度MySQL架包进行搜索下载。将下载好的架包复制到上一步建好的lib文件夹里面,并右键架包选择build path→Add to Build Path。

4、在刚刚新建的Java项目中,着手开始写Java代码进行连接。
其中MySQL驱动的写法是固定的,为 com.mysql.jdbc.Driver
URL:jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8,如:jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8,这边问号代表的连接符,后面的代码是解决数据库中文乱码的问题。
USER:你的用户名
PASSWORD:你的密码

5、连接驱动。

6、获得Connection。

7、main函数中进行测试。调用完方法之后,记得释放资源。

8、所有源码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
//MySQL驱动
private static final String DRIVER="com.mysql.jdbc.Driver"; //URL
private static final String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
//USER
private static final String USER="root";
//PASSWORD
private static final String PASSWORD="123456";
//Connection
private Connection connection=null;
//加载驱动
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//getConnection()
public Connection getConnection(){
try {
connection=DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
//使用main函数进行测试
public static void main(String[] args) {
//创建对象
DBHelper dbHelper=new DBHelper();
Connection connection=dbHelper.getConnection();
System.out.println(connection);
//释放connection资源
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection=null;
}
}
System.out.println("---------------------------------------");
System.out.println(connection);
}
}