jdbc连接MariaDB数据库

jdbc连接MariaDB数据库

1、准备好MariaDB驱动

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

 

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


SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_demo1
-- ----------------------------
DROP TABLE IF EXISTS `tb_demo1`;
CREATE TABLE `tb_demo1`  (
  `id` int(30) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tb_demo1
-- ----------------------------
INSERT INTO `tb_demo1` VALUES (1, 'admin', 'pass');
INSERT INTO `tb_demo1` VALUES (2, 'user1', 'user1');

SET FOREIGN_KEY_CHECKS = 1;

 


3、新建项目

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

项目目录结构

jdbc连接MariaDB数据库_第1张图片

 

下面直接贴代码

package com.mariadb.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 ="org.mariadb.jdbc.Driver";
		// url
		String url = "jdbc:mariadb://localhost:3306/test";
		// 用户名
		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 username,password from tb_demo1";
			// 执行查询
			rs = stmt.executeQuery(sql);
			
			// 输出查询结果
			while(rs.next()) {
				System.out.println("用户名: "+rs.getString(1)
				+"\t 密码: "+rs.getString(2));
				}
			
		} 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();
			}
				
		}		
		
	}
	
}

 

 

 

 

 

 

 

你可能感兴趣的:(MariaDB,Java)