step1:首先保证你已经安装好了mysql,并保证mysql的服务处于启动状态。(推荐使用xampp进行mysql数据的简单管理,如果你cmd管理一定要注意开启mysql服务)
step2:下载java的mysql驱动jar包,下载地址为http://dev.mysql.com/downloads/file/?id=459313,可能后期有更新的jar包。下载下来可能还有其他文件,只有mysql-connector-java-5.1.37-bin.jar这个jar文件是我们要使用的,其他不用管。
step3:创建一个java普通工程,在工程目录下创建一个db文件夹,将mysql驱动jar包放入db文件夹。如下图所示:
step4:右键工程,选择Build Path--->Configure Build Path
step6:下面编写一个连接MySQL数据库的程序:
<span style="font-size:18px;">package jdbctest;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.*;
class ConnectionSQL{
private static final String databasePath = "jdbc:mysql://localhost:3306/student";
private static final String driverPath = "com.mysql.jdbc.Driver";
private String userName = "root";
private String password = "beyonddream";
private java.sql.Connection connection = null;
public ConnectionSQL(){
try {
Class.forName(driverPath);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("加载数据库驱动成功");
}
public boolean getConnectionToSQL(){
try {
connection = DriverManager.getConnection(databasePath,userName,password);
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
public class ConnectionToMySQL {
public static void main(String[] args){
ConnectionSQL connectionSQL = new ConnectionSQL();
if(connectionSQL.getConnectionToSQL()){
System.out.println("链接数据库成功");
}else{
System.out.println("链接数据库失败");
}
}
}
</span>