Java, MySQL 및 JDBC Hello World 자습서 – MySQL에서 연결 생성, 데이터 삽입 및 데이터 검색
게시 됨: 2020-07-27
현재의 혁신적인 기술 세계에서 개인화 연결 및 활동을 수행하기 위해 Database connectivity
이 필요하지 않은 곳은 없습니다.
Facebook, Twitter 또는 기타 소셜 미디어를 사용하는 경우 사이트에서 수행하는 모든 작업은 DB에 저장될 수 있으며 관련 개인화 보기를 위해 retrieved during your next visit
.
브라우저 캐싱과 같은 몇 가지 다른 기술이 있지만 DataBase에 기본 설정을 저장하는 것도 그 중 하나입니다.
야생에는 너무나 많은 데이터베이스가 있습니다. 다음은 CouchBase, MySQL, Oracle, Cassandra, MongoDB 등입니다. 이 자습서에서는 MySQL 데이터베이스를 살펴보겠습니다.
아래 질문 중 하나가 있으면 올바른 위치에 있습니다.
- JDBC 튜토리얼 – JDBC HelloWorld MySQL
- JDBC를 사용하여 데이터베이스에 연결
- JDBC 및 MySQL 연결
- Java에서 JDBC 드라이버로 MySQL에 연결하는 방법
- JDBC를 사용하여 Java 프로그램에서 MySQL에 연결
- mysql을 사용하여 Java에서 JDBC 연결을 위한 샘플 코드
- Eclipse를 사용하여 Java에서 mysql 데이터베이스를 연결하는 방법
당신이 필요로하는 무엇입니까?
데스크탑이나 노트북에 로컬로 MySQL
을 설치해야 합니다. 기본적으로 MySQL DB와 함께 제공되는 macOS에 MAMP를 설치했습니다.
시작하자:
-
CrunchifyMySQLDBTutorial.java
클래스 생성 - 표준 DB
Connection
,PreparedStatement
및ResultSet
객체 생성 -
executeUpdate()
작업을 수행하여 테이블에 데이터 삽입 -
executeQuery()
작업을 수행하여 MySQL 테이블에서 데이터 검색 - 우리의 경우:
- 데이터베이스 이름: crunchify
- 사용자 이름: 루트
- 비밀번호: 루트
- 테이블 이름: 직원
-
Step - 1
: DB에 대한 연결을 생성합니다. JDBC 실패의 경우 오류 메시지가 발생합니다. -
Step - 2
: 데이터베이스에 3개의 레코드를 추가합니다. -
Step - 3
: 모든 레코드를 하나씩 읽고 Eclipse 콘솔에서 인쇄합니다.
JDBC MySQL에 대한 Maven 종속성
프로젝트의 pom.xml 파일에 아래 maven 종속성을 추가하십시오.
1 2 3 4 5 |
< dependency > < groupId > mysql < / groupId > < artifactId > mysql - connector - java < / artifactId > < version > 5.1.6 < / version > < / dependency > |
다음은 데이터베이스 구조입니다.

MySQL JDBC 연결을 위한 완전한 Java 코드 및 추가, 검색 작업
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
package crunchify . com . tutorial ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; /** * @author Crunchify.com * Simple Hello World MySQL Tutorial on how to make JDBC connection, Add and Retrieve Data by App Shah * */ public class CrunchifyMySQLDBTutorial { static Connection crunchifyConn = null ; static PreparedStatement crunchifyPrepareStat = null ; public static void main ( String [ ] argv ) { try { log ( "-------- Simple Crunchify Tutorial on how to make JDBC connection to MySQL DB locally on macOS ------------" ) ; makeJDBCConnection ( ) ; log ( "\n---------- Adding company 'Crunchify LLC' to DB ----------" ) ; addDataToDB ( "Crunchify, LLC." , "NYC, US" , 5 , "https://crunchify.com" ) ; addDataToDB ( "Google Inc." , "Mountain View, CA, US" , 50000 , "https://google.com" ) ; addDataToDB ( "Apple Inc." , "Cupertino, CA, US" , 30000 , "http://apple.com" ) ; log ( "\n---------- Let's get Data from DB ----------" ) ; getDataFromDB ( ) ; crunchifyPrepareStat . close ( ) ; crunchifyConn . close ( ) ; // connection close } catch ( SQLException e ) { e . printStackTrace ( ) ; } } private static void makeJDBCConnection ( ) { try { Class . forName ( "com.mysql.jdbc.Driver" ) ; log ( "Congrats - Seems your MySQL JDBC Driver Registered!" ) ; } catch ( ClassNotFoundException e ) { log ( "Sorry, couldn't found JDBC driver. Make sure you have added JDBC Maven Dependency Correctly" ) ; e . printStackTrace ( ) ; return ; } try { // DriverManager: The basic service for managing a set of JDBC drivers. crunchifyConn = DriverManager . getConnection ( "jdbc:mysql://localhost:3306/crunchify" , "root" , "root" ) ; if ( crunchifyConn ! = null ) { log ( "Connection Successful! Enjoy. Now it's time to push data" ) ; } else { log ( "Failed to make connection!" ) ; } } catch ( SQLException e ) { log ( "MySQL Connection Failed!" ) ; e . printStackTrace ( ) ; return ; } } private static void addDataToDB ( String companyName , String address , int totalEmployee , String webSite ) { try { String insertQueryStatement = "INSERT INTO Employee VALUES (?,?,?,?)" ; crunchifyPrepareStat = crunchifyConn . prepareStatement ( insertQueryStatement ) ; crunchifyPrepareStat . setString ( 1 , companyName ) ; crunchifyPrepareStat . setString ( 2 , address ) ; crunchifyPrepareStat . setInt ( 3 , totalEmployee ) ; crunchifyPrepareStat . setString ( 4 , webSite ) ; // execute insert SQL statement crunchifyPrepareStat . executeUpdate ( ) ; log ( companyName + " added successfully" ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } } private static void getDataFromDB ( ) { try { // MySQL Select Query Tutorial String getQueryStatement = "SELECT * FROM employee" ; crunchifyPrepareStat = crunchifyConn . prepareStatement ( getQueryStatement ) ; // Execute the Query, and get a java ResultSet ResultSet rs = crunchifyPrepareStat . executeQuery ( ) ; // Let's iterate through the java ResultSet while ( rs . next ( ) ) { String name = rs . getString ( "Name" ) ; String address = rs . getString ( "Address" ) ; int employeeCount = rs . getInt ( "EmployeeCount" ) ; String website = rs . getString ( "Website" ) ; // Simply Print the results System . out . format ( "%s, %s, %s, %s\n" , name , address , employeeCount , website ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } } // Simple log utility private static void log ( String string ) { System . out . println ( string ) ; } } |
산출:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-------- Simple Crunchify Tutorial on how to make JDBC connection to MySQL DB locally on macOS ------------ Congrats - Seems your MySQL JDBC Driver Registered! Connection Successful! Enjoy. Now it's time to push data ---------- Adding company 'Crunchify LLC' to DB ---------- Crunchify, LLC. added successfully Google Inc. added successfully Apple Inc. added successfully ---------- Let's get Data from DB ---------- Crunchify, LLC., NYC, US, 5, https://crunchify.com Google Inc., Mountain View, CA, US, 50000, https://google.com Apple Inc., Cupertino, CA, US, 30000, http://apple.com |