Java是通过JDBC连接Mysql数据库的。JDBC(JavaData Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
首先下载jar程序驱动包:http://www.mysql.com/downloads/connector/j
下载完之后添加到项目中如下:
右键选择Properties
添加刚才下载的jar驱动包:
添加驱动包
下一步开始连接mysql:
public class mysql连接 {
//数据库地址
public static final String url = "jdbc:Mysql://localhost:3306/openfire1?characterEncoding=utf8&useSSL=true";
//jdbc驱动
public static final String name = "com.mysql.jdbc.Driver";
//用户名
public static final String user = "root";
//数据库密码
public static final String password = "mysql123";
static Connection con;
public static void main(String []args) throws ClassNotFoundException {
try {
//加载jdbc驱动
Class.forName(name);
//连接数据库
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed()) {
System.out.println("连接成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
“?characterEncoding=utf8&useSSL=true”,这是允许SSL连接,不加的话可能会报这个错误:
WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
“数据库名”就是自己的数据库名称,前提是你已经有这个数据库了!
其实步骤也不是很复杂,但是第一次操作的话可能会绕很多弯路,比如我!