Java与MySQL的连接

  1. 下载数据库驱动文件,解压并保存至任意位置
    下载地址
  2. 新建Java项目,并将驱动文件添加到项目中
    项目名右键-->构建路径-->配置构建路径-->添加外部Jar
  3. 在项目中新建类,编写代码:
package sam_160714;

import java.sql.Connection;
import java.sql.DriverManager; //Ctrl+Shift+O  自动导入类包
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * 数据库连接实例
 * @author lenovo
 *
 */
public class Conn2Mysql {
	public Connection conn = null; // 创建Connection对象
	// 获取数据库连接方法
	public Connection getConnection() {
		try {
			long start=System.currentTimeMillis();
			Class.forName("com.mysql.jdbc.Driver"); // 加载数据库驱动
			String suffix="?useUnicode=true&characterEncoding=utf-8&useSSL=false";
			//suffix="";
			String url = "jdbc:mysql://localhost:3306/my_db_1"+suffix;
			String user = "root";
			String passWord = "admin";
			conn = DriverManager.getConnection(	url, user, passWord);
			long end=System.currentTimeMillis();
			
			if (conn != null) {
				System.out.println("数据库连接成功");
				System.out.println(conn);
				System.out.println("建立连接耗时:"+(end-start)+"毫秒");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}// 异常处理
		return conn;// 返回Connection对象
	}
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Conn2Mysql getConn = new Conn2Mysql(); // 创建GetConn对象		
		getConn.getConnection();// 调用连接数据库方法
		try {
			getConn.conn.close();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}		
	}
}

运行结果

注意

如果url不使用后缀字符串suffix,则会出现如下警告:

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.
posted @ 2016-07-14 17:06  ryanleo  阅读(395)  评论(0编辑  收藏  举报