红联Linux门户
Linux帮助

ubuntu16.04下MySQL驱动、使用eclipse链接数据库

发布时间:2017-06-22 09:32:36来源:linux网站作者:凡人
我终于完成了这个问题,下面来分享一下具体过程。
 
1、在官网上下载MySQL驱动的安装包(.tar.gz格式的),4、5M左右,这个一般没什么问题。
接下来需要将它解压,这里我是我将文件解压到了 /opt/目录下,这个问题也不大。
 
2、解压之后的文件包内容如下
wulongjian@wulongjian-Inspiron-5557:/opt/mysql-connertor$ ls
build.xml CHANGES COPYING docs mysql-connector-java-5.1.41-bin.jar README README.txt src
在该文件中重点加黑了一个jar文件,经过度娘的指导,我们需要这个文件复制到你的jdk目录中lib目录下,如果你已经安装了tomcat服务器,也可以顺便复制到你tomcat目录中lib目录下。
 
3、下载打开eclipse,进入菜单windows->prefrences,进入Java->Build Path->user libraries,选择新建,命名为mysql,如下所示:
ubuntu16.04下MySQL驱动、使用eclipse链接数据库
之后在右侧选择 Add External JARs,会看到提示内容,选择你的jar文件即可。
 
4、创建Java project,我这里命名为x,右键其,选择Build Path->,从列表中选择user library,在next界面中选择上面部署的mysql安装包即可;
3、4步骤,可能会因为版本的不同,eclipse界面显示不同,但是大概的位置是一定的,所以仔细找找肯定会找到。
 
5、编写代码验证,我的第一次代码如下:
package cn;
import java.sql.*;
public class My {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");     //加载MYSQL JDBC驱动程序   
System.out.println("Success loading Mysql Driver!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/first","root","password");
System.out.println("Success connect Mysql server!");
//select code
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from student_table2");
while (rs.next()) {
System.out.println(rs.getString("student_id"));
}
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
 
可能小白会对里面的部分代码不了解,这里重点说一个片段:
Connection connect = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/first”,”root”,”password”);
上面的DriverManager.getConnection代表获取数据库链接,括号后面是3个参数:数据库URL、用户名、用户密码,其中,数据库URL的写法如下:
jdbc:mysql://hostname:port/databasename,对于本地客户端来说,基本上就是localhost:3306不会变,如果一切正常,将会输出如下结果:
Success loading Mysql Driver!
Fri Mar 03 22:27:18 CST 2017 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.
Success connect Mysql server! 
 
本文永久更新地址:http://www.linuxdiyf.com/linux/31654.html