MySQL(MariaDB) Connector

Python 2022. 5. 5. 00:15 |
반응형

2018.11.19 - [Python] - PyMySQL

 

Python에서 원격으로 MySQL(MariaDB)을 사용해 보자.

아래 링크를 참고해 데이터베이스를 준비한다.

2021.08.28 - [Linux] - Linux(Ubuntu) MariaDB(MySQL) Server Remote Access - 데이터베이스 원격 접속

 

mysql-connector-python을 설치한다.

 

데이터베이스에는 위와 같은 데이터를 준비한다.

 

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
import mysql.connector
from mysql.connector import errorcode
 
try:
    cnx = mysql.connector.connect(host="192.168.171.20", user="root",
                                  passwd="1234", database="test_db",
                                  connection_timeout=5)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    elif err.errno == 2003# 호스트 주소가 틀리거나 문제가 있다면
        print("Connection error(Timeout)")
    else:
        print(err)
else:   # 데이터베이스 접속 오류가 없다면
    cursor = cnx.cursor()
    
    query = ("SELECT * FROM test_tb")
    cursor.execute(query)
    for (id, name, age) in cursor:
        print("id: {}, name: {}, age: {}".format(id, name, age))
            
    #for row in cursor:
    #    print(row)
 
    cursor.close()
    cnx.close()
 

 

소스를 입력하고 실행한다.

 

데이터베이스의 내용이 출력된다.

 

※ 참고

MySQL Connector/Python Developer Guide

반응형
Posted by J-sean
:
반응형

C#에 SQLite 데이터베이스를 연동해 보자.

 

System.Data.SQLite를 설치한다.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Data.SQLite;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 데이터베이스 생성 및 열기. 생성하려는 데이터베이스가 존재하면 열기만 한다.
                SQLiteConnection connection = new SQLiteConnection("Data Source=" + Environment.CurrentDirectory + "/test.db");
                connection.Open();
 
                SQLiteCommand command = new SQLiteCommand(connection);
                command.CommandText = "CREATE TABLE IF NOT EXISTS test (" +
                    "id INTEGER PRIMARY KEY, " +
                    "name TEXT NOT NULL, " +
                    "birthday TEXT NOT NULL)";
                // Execute the command and return the number of rows inserted/updated affected by it. 
                command.ExecuteNonQuery();
 
                // 이미 존재하는 데이터는 'OR IGNORE'에 의해 무시된다.
                command.CommandText = "INSERT OR IGNORE INTO test (id, name, birthday) VALUES (1, 'sean', '2020-01-20'), " +
                    "(2, 'david', '2021-11-03'), " +
                    "(3, 'john', '2022-05-17')";
                int rowCount = command.ExecuteNonQuery();
                Console.WriteLine("The number of rows inserted/updated affected by it: " + rowCount + "\n");
 
                command.CommandText = "SELECT * FROM test";
                SQLiteDataReader reader = command.ExecuteReader();
                // Reads the next row from the resultset. True if a new row was successfully loaded and is ready for processing
                while (reader.Read())
                {
                    Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}, Birthday: {reader.GetString(2)}");
                }
                // 다음 SQLiteCommand 사용을 위해 SQLiteDataReader 사용이 끝나면 종료해야 한다.
                reader.Close();
 
                // The date() function returns the date in this format: YYYY-MM-DD.
                // The julianday() function returns the Julian day - the number of days since noon in Greenwich
                // on November 24, 4714 B.C. (Proleptic Gregorian calendar).
                command.CommandText = "SELECT JULIANDAY(DATE('NOW')) - JULIANDAY(DATE(birthday)) FROM test WHERE id=2";
                int days = Convert.ToInt32(command.ExecuteScalar());
                Console.WriteLine("David's birthday was " + days + " days ago.");
 
                connection.Close();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

실행하면 데이터가 출려된다.

 

다시 한 번 실행하면 'OR IGNORE'에 의해 INSERT 명령어는 무시된다.

 

 

실행파일 폴더에 test.db가 생성되었다.

※ 참고

SQLite Download Page for Documentaion and Commend-Line Tools.

 

반응형
Posted by J-sean
:
반응형

C#에 MariaDB(MySQL) 데이터베이스를 연동해 보자.

 

NuGet Package Manager에서 MySql.Data를 설치한다.

 

위와 같은 데이터베이스를 준비한다.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using MySql.Data.MySqlClient;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string server = "192.168.171.200";
            string user = "root";
            string database = "member_db";
            string password = "1234";
            string connStr = $"server={server};user={user};database={database};port=3306;password={password}";
            MySqlConnection conn = new MySqlConnection(connStr);
 
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();
                Console.WriteLine("Connected to MySQL.");
                // Perform database operations
 
                string sql = "SELECT * FROM member";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();
                // ExecuteReader to query the database.
                // ExecuteNonQuery to insert, update, and delete data.
 
                while (rdr.Read())
                {
                    Console.WriteLine($"ID: {rdr[0]}, Name: {rdr[1]}, Age: {rdr[2]}");
                }
                rdr.Close();
 
                sql = "SELECT name FROM member WHERE id='id2'";
                cmd = new MySqlCommand(sql, conn);
                object result = cmd.ExecuteScalar();
                // ExecuteScalar to return a single value.
 
                if (result != null)
                {
                    string name = Convert.ToString(result);
                    Console.WriteLine($"Name of id2: {name}.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
 
            conn.Close();
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

요청한 데이터를 표시한다.

※ 참고

MySQL Connector/NET Developer Guide

 

반응형
Posted by J-sean
:
반응형

아래 링크를 참고해 MariaDB(MySQL)에 저장된 데이터를 확인하는 PHP 웹페이지를 만들어 보자.

2022.02.07 - [Linux] - Connect PHP to MariaDB(MySQL) - MariaDB(MySQL) PHP 연동 1

 

확인할 데이터 정보를 입력하는 index.php 소스를 작성한다.

 

서버에 접속하고 확인할 데이터를 가져오는 data_check.php 소스를 작성한다.

 

서버에 접속하면 ID와 Name을 입력할 수 있는 텍스트 박스가 표시된다.

 

확인하고 싶은 정보를 입력하고 Check 버튼을 클릭한다.

 

 

입력한 정보와 함께 Age가 표시된다.

 

잘못된 정보를 입력해 보자.

 

데이터가 제대로 표시되지 않는다.

 

반응형
Posted by J-sean
:
반응형

PHP에 MariaDB(MySQL)를 연동해 보자.

 

MariaDB(MySQL), PHP 뿐만 아니라 php-mysql도 필요하다.

 

위와 같이 member_db 데이터베이스에 member 테이블을 만든다.

 

데이터베이스 정보를 읽어오는 php 소스를 작성한다.

 

서버에 접속하면 데이터베이스 내용이 표시된다.

 

 

데이터베이스 접속 오류시 표시 내용 (잘못된 암호)

 

반응형
Posted by J-sean
:

MariaDB(MySQL) C API

C, C++ 2021. 8. 29. 15:44 |
반응형

MariaDB도 MySQL과 거의 비슷한 방식으로 C API를 사용할 수 있다.

2018.11.20 - [C, C++] - MySQL C API

기본적인 내용은 MySQL C API와 거의 같고 아래와 같이 Project Property Pages에 Include/Library Directories 및 파일 이름만 변경 된다.

 

  • Project - XXX Properties... - Configuration Properties - C/C++ - General - Additional Include Directories - C:\Program Files\MariaDB 10.6\include
  • Project - XXX Properties... - Configuration Properties - Linker - General - Additional Library Directories - C:\Program Files\MariaDB 10.6\lib

 

아래 두 파일은 프로젝트 폴더에 복사한다. (libmysql.lib, libmysql.dll 이 아니다)

  • libmariadb.lib
  • libmariadb.dll

 

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
#include <stdio.h>
#include <mysql/mysql.h>
 
#pragma comment (lib, "libmariadb.lib")
 
int main()
{
    MYSQL mysql;            // MariaDB(MySQL) 정보를 담을 구조체
    MYSQL* mysqlPtr = NULL;    // MariaDB(MySQL) connection 핸들러
    MYSQL_RES* Result = NULL;        // 쿼리 성공시 결과를 담는 구조체 포인터
    MYSQL_ROW Row;            // 쿼리 성공시 결과로 나온 행의 정보를 담는 구조체
    int stat;                // 쿼리 요청 후 결과
 
    printf("MariaDB(MySQL) Client Version: %s\n\n", mysql_get_client_info());
    // Returns client version information as a string
 
    mysql_init(&mysql); // Gets or initializes a MYSQL structure 
 
    mysqlPtr = mysql_real_connect(&mysql, "127.0.0.1""root""password""database"3306, (char*)NULL0);
    // Connects to a MariaDB(MySQL) server
 
    if (mysqlPtr == NULL)
    {
        printf("MariaDB(MySQL) connection error: %s\n", mysql_error(&mysql));
        // Returns the error message for the most recently invoked MariaDB(MySQL) function
        return 1;
    }
 
    // MariaDB(MySQL)에서 사용하는 문자세트를 Visual Studio가 사용하는 euc-kr로 바꾸기
    mysql_query(mysqlPtr, "set session character_set_connection=euckr");
    mysql_query(mysqlPtr, "set session character_set_results=euckr");
    mysql_query(mysqlPtr, "set session character_set_client=euckr");
 
    const char* Query = "SELECT * FROM table";
    stat = mysql_query(mysqlPtr, Query);    // Executes an SQLquery specified as a null-terminated string
    if (stat != 0)
    {
        printf("MariaDB(MySQL) connection error: %s\n", mysql_error(&mysql));
        return 1;
    }
 
    Result = mysql_store_result(mysqlPtr);    // Retrieves a complete result set to the client
    printf("Number of rows: %I64d\nNumber of columns: %d\n\n", Result->row_count, Result->field_count);
    while ((Row = mysql_fetch_row(Result)) != NULL)    // Fetches the next row from the result set 
    {
        for (unsigned int i = 0; i < Result->field_count; i++)
        {
            printf("%s ", Row[i]);
        }
        printf("\n");
    }
    
    mysql_free_result(Result);    // Frees memory used by a result set
    mysql_close(mysqlPtr);    // Closes a server connection
 
    return 0;
}
 

 

반응형
Posted by J-sean
:
반응형

리눅스에 MariaDB(MySQL)를 설치하고 데이터베이스 서버에 원격으로 접속 해 보자.

 

MariaDB 서버 및 클라이언트를 설치한다.

윈도우용 MariaDB 설치 파일은 서버와 클라이언트를 함께 설치 하지만 리눅스(우분투)용 MariaDB는 따로 설치해야 한다.

 

설치가 완료 되었다면 클라이언트를 실행해 본다.

 

클라이언트 실행에 문제가 없다면 설정파일을 열어준다.

MariaDB는 기본적으로 원격 접속이 막혀있다. 설정을 변경하기 위해 아래 경로의 파일을 수정해야 한다.

/etc/mysql/mariadb.conf.d/50-server.cnf

 

'bind-address = 127.0.0.1' 을 주석처리 하고 저장한다.

※ 방화벽이 설정되어 있다면 MariaDB가 사용하는 포트를 열어준다.

sudo ufw allow 3306

 

 

MariaDB(MySQL) 사용 포트 확인.

show global variables like 'port';

 

서버에 접속할 클라이언트가 사용하는 IP 주소를 확인한다.

데이터베이스 서버에 접속할 클라이언트의 IP 주소를 미리 서버에 등록해야 한다.

서버를 WMware 에 설치했기 때문에 IP 주소는 192.168.0.16 이 아니라 192.168.171.1 을 사용한다.

 

서버가 설치된 컴퓨터에서 사용자 정보가 들어 있는 mysql.user 테이블을 확인해 본다.

로컬호스트의 root 사용자(리눅스의 root 사용자와 무관)만 등록되어 있다. 로컬호스트 이므로 원격으로 접속할 수 없다.

 

모든 데이터베이스에 모든 권한을 가지고 192.168.171.XXX에서 접속하는 sean이라는 사용자를 만든다. password는 1234.

유동 IP의 경우 재부팅 할 때마다 IP가 바뀔 수 있으므로 192.168.171.XXX 범위의 IP 주소를 가지는 컴퓨터는 모두 접속 할 수 있도록 설정 한다.

grant all on *.* to sean@'192.168.171.%' identified by '1234';

 

 

원격 사용자 설정 후, MariaDB를 재시작하고 데이터베이스 서버가 설치된 컴퓨터의 IP 주소(192.168.171.200)를 확인한다.

sudo systemctl restart mariadb

 

클라이언트에서 서버로 접속한다.

MariaDB(MySQL) 클라이언트를 실행하고 아래와 같이 입력한다.

mysql -h (IP 주소) -u (사용자) -p

 

-p 옵션에 password를 바로 입력해도 된다.

-p 옵션에 password는 공백 없이 붙여야 한다.

-p 1234 (X)

-p1234 (O)

 

반응형
Posted by J-sean
: