Programing

Java를 MySQL 데이터베이스에 연결

lottogame 2020. 3. 12. 08:08
반응형

Java를 MySQL 데이터베이스에 연결


Java에서 MySQL 데이터베이스에 어떻게 연결합니까?

시도하면

java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)

또는

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

또는

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

DriverManager일을하는 상당히 오래된 방법입니다. 더 좋은 방법은 DataSource앱 서버 컨테이너가 이미 구성되어 있는지 확인하여을 얻는 것입니다.

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

또는 데이터베이스 드라이버에서 직접 인스턴스화 및 구성 :

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");

그런 다음 위와 같이 연결을 얻습니다.

Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();

다음은 MySQL 및 JDBC 설치 방법 및 사용 방법에 대한 단계별 설명입니다.

  1. MySQL 서버를 다운로드 하여 설치하십시오 . 그냥 평소처럼하세요. 포트 번호를 변경할 때마다 기억하십시오. 기본적으로3306입니다.

  2. JDBC 드라이버를 다운로드 하고 classpath에 넣고 ZIP 파일을 추출한 후 포함하는 JAR 파일을 클래스 경로에 넣으십시오. 공급 업체별 JDBC 드라이버는 JDBC API를 구체적으로 구현 한 것입니다( 여기의 자습서 ).

    Eclipse 또는 Netbeans와 같은 IDE를 사용하는 경우 JAR 파일을 라이브러리프로젝트 특성 빌드 경로라이브러리추가하여 클래스 경로에 추가 할 수 있습니다 .

    명령 콘솔에서 "일반 바닐라"를 수행하는 경우 Java 애플리케이션을 실행할 때 -cp또는 -classpath인수 에서 JAR 파일의 경로를 지정해야 합니다.

    java -cp.; / path / to / mysql-connector.jar com.example.YourClass

    .추가 단지가 현재 뿐만 아니라 그래서 찾을 수있는 클래스 경로에 디렉토리를 com.example.YourClass하고는 ;이 윈도우에서와 같이 클래스 패스 분리기이다. 유닉스에서는 클론을 :사용해야합니다.

  3. MySQL 에서 데이터베이스작성하십시오 . 데이터베이스를 만들어 봅시다 javabase. 물론 World Domination을 원하니 UTF-8도 사용하자.

    CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    
  4. Java 용 사용자작성하고 액세스 권한을 부여 하십시오 . 단순히 사용root하는 것은 나쁜 습관이기 때문입니다.

    CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';
    

    예, java사용자 이름이며 password여기에 비밀번호입니다.

  5. JDBC URL을 결정 하십시오 . Java를 사용하여 MySQL 데이터베이스를 연결하려면 다음 구문의 JDBC URL이 필요합니다.

    jdbc : mysql : // 호스트 이름 : 포트 / 데이터베이스 이름
    • hostname: MySQL 서버가 설치된 호스트 이름입니다. Java 코드를 실행하는 동일한 시스템에 설치되어 있으면을 사용할 수 있습니다 localhost. 와 같은 IP 주소 일 수도 있습니다 127.0.0.1. 연결 문제가 발생하고 해결하는 127.0.0.1대신 사용 하는 경우 localhost네트워크 / DNS / 호스트 구성에 문제가있는 것입니다.

    • port: MySQL 서버가 청취하는 TCP / IP 포트. 이것은 기본적으로 3306입니다.

    • databasename: 연결하려는 데이터베이스의 이름입니다. 그렇습니다 javabase.

    최종 도착 URL은 다음과 같아야합니다.

    jdbc : mysql : // localhost : 3306 / javabase
  6. Java를 사용하여 MySQL에 대한 연결테스트하십시오 . main()연결을 테스트하는메소드를사용하여 간단한 Java 클래스를 작성하십시오.

    String url = "jdbc:mysql://localhost:3306/javabase";
    String username = "java";
    String password = "password";
    
    System.out.println("Connecting database...");
    
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        System.out.println("Database connected!");
    } catch (SQLException e) {
        throw new IllegalStateException("Cannot connect the database!", e);
    }
    

    를 받으면 SQLException: No suitable driverJDBC 드라이버가 전혀 자동로드되지 않았거나 JDBC URL이 잘못되었다는 의미입니다 (예 :로드 된 드라이버가 인식하지 못함). 일반적으로 JDBC 4.0 드라이버는 런타임 클래스 경로에 드롭 할 때 자동으로로드되어야합니다. 하나와 다른 것을 제외하기 위해 항상 다음과 같이 수동으로로드 할 수 있습니다.

    System.out.println("Loading driver...");
    
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded!");
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Cannot find the driver in the classpath!", e);
    }
    

    점을 유의 newInstance()호출이되어 있지 여기가 필요했습니다. 그것은 단지 오래되고 버그가있는 것 org.gjt.mm.mysql.Driver입니다. 여기에 설명하십시오 . 이 행이 발생 ClassNotFoundException하면 JDBC 드라이버 클래스를 포함하는 JAR 파일이 클래스 경로에 배치되지 않습니다.

    연결 하기 전에 매번 드라이버를로드 할 필요는 없습니다 . 응용 프로그램 시작 중 한 번만으로 충분합니다.

    당신이 얻을 경우 SQLException: Connection refusedConnection timed out또는 MySQL의 특정을 CommunicationsException: Communications link failure, 다음은 DB가 전혀 도달 할 수없는 것을 의미한다. 다음 원인 중 하나 이상이 발생할 수 있습니다.

    1. JDBC URL의 IP 주소 또는 호스트 이름이 잘못되었습니다.
    2. 로컬 DNS 서버가 JDBC URL의 호스트 이름을 인식하지 못합니다.
    3. JDBC URL에서 포트 번호가 누락되었거나 잘못되었습니다.
    4. DB 서버가 다운되었습니다.
    5. DB 서버는 TCP / IP 연결을 허용하지 않습니다.
    6. DB 서버에 연결이 부족합니다.
    7. Java와 DB 사이에 방화벽이나 프록시와 같은 연결이 차단되고 있습니다.

    둘 중 하나를 해결하려면 다음 조언을 따르십시오.

    1. 로 확인하고 테스트하십시오 ping.
    2. 대신 DNS를 새로 고치거나 JDBC URL에서 IP 주소를 사용하십시오.
    3. my.cnfMySQL DB를 기반으로 확인하십시오 .
    4. DB를 시작하십시오.
    5. mysqld가 --skip-networking option. 없이 시작되었는지 확인하십시오 .
    6. DB를 다시 시작하고에서 연결을 닫도록 코드를 수정하십시오 finally.
    7. 방화벽을 비활성화하거나 포트를 허용 / 전달하도록 방화벽 / 프록시를 구성하십시오.

    를 닫는 Connection것이 매우 중요합니다. 연결을 닫지 않고 짧은 시간에 많은 연결을 유지하면 데이터베이스 연결이 끊어지고 응용 프로그램이 중단 될 수 있습니다. 항상 Connectionin try-with-resources문을 획득하십시오 . 아니면 아직 자바 7에 명시 적으로 가까운 그것에하지 않은 경우 finally(A)의 try-finally블록. 닫는 finally것은 예외가 발생했을 때도 닫히는 것입니다. 이것은 또한 적용 Statement, PreparedStatementResultSet.

연결성 문제까지는 그 정도였습니다. 당신은 찾을 수 있습니다 여기에 기본 DAO 클래스의 도움으로 데이터베이스에 자바 모델 객체 fullworthy 더 진보 된 방법을로드하는 튜토리얼 및 저장합니다.


DB 연결에 싱글 톤 패턴을 사용하는 것은 나쁜 접근법입니다. 다른 질문들 중 하나를 참조하십시오 : http://stackoverflow.com/q/9428573/ . 이것은 첫 번째 실수입니다.


데이터베이스 상수 초기화

상수 속성 데이터베이스 사용자 이름, 비밀번호, URL 및 드라이버, 폴링 제한 등을 작성하십시오.

// init database constants
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit

연결 및 속성 초기화

연결이 설정되면 재사용 목적으로 보관하는 것이 좋습니다.

// init connection object
private Connection connection;
// init properties object
private Properties properties;

속성 만들기

속성 개체는 연결 정보를 보유하고 있으며 이미 설정되어 있는지 확인하십시오.

// create properties
private Properties getProperties() {
    if (properties == null) {
        properties = new Properties();
        properties.setProperty("user", USERNAME);
        properties.setProperty("password", PASSWORD);
        properties.setProperty("MaxPooledStatements", MAX_POOL);
    }
    return properties;
}

데이터베이스 연결

이제 초기화 된 상수와 속성을 사용하여 데이터베이스에 연결하십시오.

// connect database
public Connection connect() {
    if (connection == null) {
        try {
            Class.forName(DATABASE_DRIVER);
            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
        } catch (ClassNotFoundException | SQLException e) {
            // Java 7+
            e.printStackTrace();
        }
    }
    return connection;
}

데이터베이스 연결 끊기

데이터베이스 작업이 끝나면 연결을 닫으십시오.

// disconnect database
public void disconnect() {
    if (connection != null) {
        try {
            connection.close();
            connection = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

모두 함께

MysqlConnectdatabase_name, username 및 password 등을 변경 한 후이 클래스를 직접 사용하십시오 .

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MysqlConnect {
    // init database constants
    private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String MAX_POOL = "250";

    // init connection object
    private Connection connection;
    // init properties object
    private Properties properties;

    // create properties
    private Properties getProperties() {
        if (properties == null) {
            properties = new Properties();
            properties.setProperty("user", USERNAME);
            properties.setProperty("password", PASSWORD);
            properties.setProperty("MaxPooledStatements", MAX_POOL);
        }
        return properties;
    }

    // connect database
    public Connection connect() {
        if (connection == null) {
            try {
                Class.forName(DATABASE_DRIVER);
                connection = DriverManager.getConnection(DATABASE_URL, getProperties());
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    // disconnect database
    public void disconnect() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

사용하는 방법?

데이터베이스 클래스를 초기화하십시오.

// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();

코드의 다른 곳에 ...

String sql = "SELECT * FROM `stackoverflow`";
try {
    PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
    ... go on ...
    ... go on ...
    ... DONE ....
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    mysqlConnect.disconnect();
}

이것은 모두입니다 :) 개선해야 할 것이 있으면 편집하십시오! 이것이 도움이 되길 바랍니다.


String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";

// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);

다음은 MySQL 데이터베이스에서 데이터를 가져 오는 데 필요한 최소값입니다.

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
   ("jdbc:mysql://localhost:3306/foo", "root", "password");

Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();

취향에 맞게 예외 처리, 구성 등을 추가하십시오.


useSSL을 사용한 MySQL JDBC 연결.

private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private String connectToDb() throws Exception {
   String jdbcDriver = "com.mysql.jdbc.Driver";
   String dbUrl = "jdbc:mysql://" + db_server  +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
    String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
    ResultSet resultSet = statement.executeQuery(query);
    resultSet.next();
    return resultSet.getString(1);
}

클래스 패스에 mysql 커넥터 jar이 있어야합니다.

Java JDBC API에서는 데이터베이스로 모든 것을 만듭니다. JDBC를 사용하여 Java 애플리케이션을
1에 작성할 수 있습니다 . 쿼리를 보내거나 SQL을 DB (모든 관계형 데이터베이스)에 업데이트합니다. 2. DB에서 결과를 검색하고 처리합니다.

아래 3 단계를 통해 모든 데이터베이스에서 데이터를 검색 할 수 있습니다.

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

while (rs.next()) {
    int x = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
}

짧고 달콤한 코드.

try
    {       
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver Loaded");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
        //Database Name - testDB, Username - "root", Password - ""
        System.out.println("Connected...");         
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

SQL Server 2012의 경우

try
    {
        String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123"; 
       //KHILAN is Host and 1433 is port number     
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        System.out.println("Driver Loaded");
        conn = DriverManager.getConnection(url);
        System.out.println("Connected...");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

Java 애플리케이션에서 MySQL 데이터베이스를 연결하는 모든 단계는 여기 에서 볼 수 있습니다 . 다른 데이터베이스의 경우 첫 단계에서만 드라이버를 변경하면됩니다. 데이터베이스에 대한 올바른 경로와 올바른 사용자 이름 및 비밀번호를 제공해야합니다.

http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA 방문


Connection나는 얼마 전에 사용했지만 가장 쉬운 방법처럼 보였지만 거기에 if진술 을하는 것이 좋습니다.

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);
if (con != null){
 //..handle your code there 
}

아니면 그런 식으로 :)

아마 어떤 경우가 있지만 getConnection리턴 할 수 있습니다 null:)


MySql JDBC 연결 :

Class.forName("com.mysql.jdbc.Driver");     

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");         
Statement stmt=con.createStatement();            
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");  

어떻게
  • 빠른 샘플을 실행하도록 드라이버를 설정하려면
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:

No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
  • CLASSPATH를 설정하려면

방법 1 : CLASSPATH 변수를 설정하십시오.

export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile

위의 명령에서 CLASSPATH를 현재 폴더 및 mysql-connector-java-VERSION.jar 파일로 설정했습니다. 따라서 java MyClassFile명령이 실행되면 Java 응용 프로그램 시작 관리자는 모든 Java 클래스를 CLASSPATH에로드하려고 시도합니다. 그리고 Drive클래스 => BOOM 오류가 사라졌습니다.

방법 2 :

java -cp .:mysql-connector-java-VERSION.jar MyClassFile

참고 : Class.forName ( "com.mysql.jdbc.Driver"); 2019 년 4 월 현재이 기능은 더 이상 사용되지 않습니다.

이것이 누군가를 도울 수 있기를 바랍니다!


짧은 코드

public class DB {

    public static Connection c;

    public static Connection getConnection() throws Exception {
        if (c == null) {
            Class.forName("com.mysql.jdbc.Driver");
            c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
        }
        return c;
    }

    // Send data TO Database
    public static void setData(String sql) throws Exception {
        DB.getConnection().createStatement().executeUpdate(sql);
    }

    // Get Data From Database
    public static ResultSet getData(String sql) throws Exception {
        ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
        return rs;
    }
}

참고 URL : https://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database

반응형