jdbc连接MySQL数据库

1、准备好mysql驱动

下载链接:https://dwz.cn/WJ10BClO

 

2、在数据库中创建数据库test以及表


SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person`  (
  `PersonId` int(11) NOT NULL,
  `FirstName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `LastName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`PersonId`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES (100001, '张', '三');
INSERT INTO `person` VALUES (100002, '李', '四');
INSERT INTO `person` VALUES (100003, '王', '五');
INSERT INTO `person` VALUES (100004, '马', '六');
INSERT INTO `person` VALUES (100005, '陈', '七');

SET FOREIGN_KEY_CHECKS = 1;

 

3、新建项目

准备好链接之后,这里用的jdk1.8,eclipse新建一个项目

项目目录结构

jdbc连接MySQL数据库_配置参数

 

下面直接贴代码

package com.mysql.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectDemo1 {

	public static void main(String[] args) {
		
		// 数据库驱动
		String driver ="com.mysql.jdbc.Driver";
		// 从配置参数中获取数据库url,注意加上编码字符集
		String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
		// 从配置参数中获取用户名
		String user = "root";
		// 从配置参数中获取密码
		String pass = "root";
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		// 注册驱动
		try {
			// 加载数据库驱动
			Class.forName(driver);
			// 获取数据库连接
			conn = DriverManager.getConnection(url,user,pass);
			// 创建Statement对象
			stmt = conn.createStatement();
			// 查询
			String sql = "select * from person";
			// 执行查询
			rs = stmt.executeQuery(sql);
			
			// 输出查询结果
			while(rs.next()) {
				System.out.println(" id号: "+rs.getString(1)
				+"\t 姓: "+rs.getString(2)
				+"\t 名: "+rs.getString(3));
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭结果
				if(rs!=null) {
					rs.close();
				}
				// 关闭载体
				if(stmt!=null) {
					stmt.close();
				}
				// 关闭连接
				if(conn!=null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
				
		}		
		
	}
	
}