MariaDB와 애플리케이션 연동

MariaDB와 애플리케이션 연동

1️⃣ Python (SQLAlchemy, PyMySQL)과 연동

Python에서 MariaDB 사용

Python은 PyMySQLSQLAlchemy와 같은 라이브러리를 사용하여 MariaDB와 쉽게 연동할 수 있습니다.

1.1 PyMySQL 사용

PyMySQL은 Python에서 MariaDB에 연결할 수 있는 라이브러리입니다.

PyMySQL 설치
pip install pymysql
MariaDB 연결 예제
import pymysql

# MariaDB 연결
connection = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    database='my_database'
)

# 쿼리 실행
cursor = connection.cursor()
cursor.execute("SELECT * FROM employees")
for row in cursor.fetchall():
    print(row)

connection.close()

1.2 SQLAlchemy 사용

SQLAlchemy는 Python의 강력한 ORM(Object Relational Mapper)으로 MariaDB와의 연동을 돕습니다.

SQLAlchemy 설치
pip install sqlalchemy pymysql
MariaDB 연결 예제
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# MariaDB 연결 URL
DATABASE_URL = "mysql+pymysql://root:password@localhost/my_database"

# SQLAlchemy 엔진 생성
engine = create_engine(DATABASE_URL, echo=True)

# ORM 세션 생성
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 기본 베이스 생성
Base = declarative_base()

# 예시 쿼리 실행
session = SessionLocal()
result = session.execute("SELECT * FROM employees")
for row in result:
    print(row)

2️⃣ Node.js (Sequelize, MySQL2)와 연동

Node.js에서 MariaDB 사용

Node.js는 Sequelize ORM과 MySQL2 드라이버를 사용하여 MariaDB와 쉽게 연동할 수 있습니다.

2.1 Sequelize 사용

Sequelize는 Node.js에서 MariaDB를 쉽게 다룰 수 있게 도와주는 ORM입니다.

Sequelize 설치
npm install sequelize mysql2
MariaDB 연결 예제
const { Sequelize, DataTypes } = require('sequelize');

// MariaDB 연결
const sequelize = new Sequelize('my_database', 'root', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

// 모델 정의
const Employee = sequelize.define('Employee', {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  position: {
    type: DataTypes.STRING
  },
  salary: {
    type: DataTypes.DECIMAL
  }
});

// 데이터 조회
async function fetchEmployees() {
  const employees = await Employee.findAll();
  console.log(employees);
}

fetchEmployees();

2.2 MySQL2 사용

MySQL2는 MariaDB와의 연결을 위한 MySQL 드라이버입니다.

MySQL2 설치
npm install mysql2
MariaDB 연결 예제
const mysql = require('mysql2');

// MariaDB 연결
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'my_database'
});

// 데이터 조회
connection.query('SELECT * FROM employees', (err, results) => {
  if (err) throw err;
  console.log(results);
});

connection.end();

3️⃣ Java (JDBC, Hibernate)와 연동

Java에서 MariaDB 사용

Java는 JDBC를 사용하여 MariaDB와 연동할 수 있으며, Hibernate를 사용하면 ORM을 통해 더 편리하게 데이터베이스와 상호작용할 수 있습니다.

3.1 JDBC 사용

JDBC는 Java에서 데이터베이스에 연결할 수 있는 표준 API입니다.

MariaDB JDBC 드라이버 설치
<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.7.3</version>
</dependency>
JDBC 연결 예제
import java.sql.*;

public class MariaDBExample {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mariadb://localhost:3306/my_database";
        String user = "root";
        String password = "password";

        Connection connection = DriverManager.getConnection(url, user, password);
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }

        connection.close();
    }
}

3.2 Hibernate 사용

Hibernate는 Java의 ORM 프레임워크로, MariaDB와의 연동을 더욱 간단하게 만들어 줍니다.

Hibernate 설정 파일 (hibernate.cfg.xml)
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mariadb://localhost:3306/my_database</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
    </session-factory>
</hibernate-configuration>
Hibernate 연동 예제
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateExample {
    public static void main(String[] args) {
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Employee.class).buildSessionFactory();
        Session session = factory.getCurrentSession();

        session.beginTransaction();
        Employee emp = session.get(Employee.class, 1);
        System.out.println(emp);
        session.getTransaction().commit();
    }
}

4️⃣ PHP (PDO, MySQLi)와 연동

PHP에서 MariaDB 사용

PHP는 PDOMySQLi를 사용하여 MariaDB와 연동할 수 있습니다.

4.1 PDO 사용

PDO는 PHP에서 데이터베이스에 안전하게 연결하고 작업할 수 있는 라이브러리입니다.

MariaDB 연결 예제
<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'root', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $pdo->query('SELECT * FROM employees');
    while ($row = $stmt->fetch()) {
        echo $row['name'] . "\n";
    }
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>

4.2 MySQLi 사용

MySQLi는 PHP에서 MariaDB에 연결할 수 있는 또 다른 방법입니다.

MariaDB 연결 예제
<?php
$mysqli = new mysqli("localhost", "root", "password", "my_database");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$result = $mysqli->query("SELECT * FROM employees");
while ($row = $result->fetch_assoc()) {
    echo $row['name'] . "\n";
}

$mysqli->close();
?>

5️⃣ Spring Boot와 MariaDB 연동

Spring Boot에서 MariaDB 사용

Spring Boot는 Spring Data JPAMariaDB를 쉽게 연동할 수 있는 라이브러리를 제공합니다.

5.1 의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.7.3</version>
</dependency>

5.2 application.properties 설정

spring.datasource.url=jdbc:mariadb://localhost:3306/my_database
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

5.3 사용자 엔티티 생성

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {
    @Id
    private Long id;
    private String name;
    private String position;
    private Double salary;

    // getters and setters
}

6️⃣ Golang (GORM, MySQL Driver)과 연동

Golang에서 MariaDB 사용

Golang은 GORM ORM과 MySQL 드라이버를 사용하여 MariaDB와 연동할 수 있습니다.

6.1 GORM 사용

GORM은 Golang의 ORM 라이브러리로 MariaDB와 쉽게 연동할 수 있습니다.

GORM 설치
go get -u github.com/jinzhu/gorm
go get -u github.com/jinzhu/gorm/dialects/mysql
MariaDB 연결 예제
package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Employee struct {
    ID     uint
    Name   string
    Position string
    Salary float64
}

func main() {
    db, err := gorm.Open("mysql", "root:password@tcp(localhost:3306)/my_database")
    if err != nil {
        fmt.Println("Connection failed:", err)
    }
    defer db.Close()

    var employees []Employee
    db.Find(&employees)
    fmt.Println(employees)
}

RSS Feed
마지막 수정일자