반응형

MySQL(MariaDB)과 구글 차트를 연동해 보자.

 

아래 내용을 참고해 웹서버와 데이터베이스를 준비한다.

2021.08.25 - [Linux] - Linux(Ubuntu) Build Your Own Web Server - 리눅스(우분투)로 웹서버 만들기

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

(데이터베이스는 로컬로 사용하므로 원격 설정을 할 필요는 없다)

 

위와 같은 데이터베이스와 테이블을 생성한다.

 

시간, 온도, 습도 데이터를 적당히 입력한다.

 

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
<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!--
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    -->
 
    <?php
        // 에러가 발생하면 내용 표시
        error_reporting(E_ALL);
        ini_set('display_errors''1');
 
        $mysql_host = "localhost";
        $mysql_user = "root";
        $mysql_password = "1234";
        $mysql_db = "test_db";
 
        $conn = mysqli_connect($mysql_host$mysql_user$mysql_password$mysql_db);
        if (!$conn) {
            die("Database Connect Error: " . mysqli_connect_error());
        }
            
        //echo "Database Connected.<br><br>";
            
        $sql = "SELECT * FROM test_tb";
        $result = mysqli_query($conn$sql);
        
        if (mysqli_num_rows($result> 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data_array[] = $row;
            }
            $chart = json_encode($data_array);
        } else {
            echo "No Data";
        }
        
        //echo $chart;
 
        mysqli_close($conn);
    ?>
 
    <script type="text/javascript">
        google.charts.load('current', { packages: ['corechart''line'] });
        google.charts.setOnLoadCallback(drawChart);
        
        function drawChart() {
            var chart_array = <?php echo $chart; ?>;
            //console.log(JSON.stringify(chart_array))
            var header = ['dt''temp''humid'];
            var row = "";
            var rows = new Array();
            jQuery.each(chart_array, function(index, item) {
                row = [
                    item.dt,
                    Number(item.temp),
                    Number(item.humid)
                ];
                rows.push(row); 
            });
 
            var jsonData = [header].concat(rows);
            var data = new google.visualization.arrayToDataTable(jsonData);
            var options = {
                title: 'Temperaure & Humid',
                hAxis: {
                    title: 'Time'
                },
                series: {
                    0: { targetAxisIndex: 0 },
                    1: { targetAxisIndex: 1 }
                },
                vAxes: {
                    0: {
                        title: 'Temperature',
                        viewWindow: { min: -30, max: 50 }
                    },
                    1: {
                        title: 'Humid',
                        viewWindow: { min: 30, max: 100 }
                    }
                }
                //,
                //curveType: 'function',
                //legend: { position: 'bottom' }
            };
 
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="chart_div" style="width: 900px; height: 500px"></div>
</body>
</html>
 

 

소스를 입력하고 웹서버에 저장한다.(/var/www/html/index.php)

 

웹서버에 접속하면 위와 같은 그래프가 표시된다.

 

 

X축 레이블을 좀 더 보기 편하게 바꾸고 테이블 차트도 추가해 보자.

 

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
<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!--
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    -->
 
    <?php
        // 에러가 발생하면 내용 표시
        error_reporting(E_ALL);
        ini_set('display_errors''1');
 
        $mysql_host = "localhost";
        $mysql_user = "root";
        $mysql_password = "1234";
        $mysql_db = "test_db";
 
        $conn = mysqli_connect($mysql_host$mysql_user$mysql_password$mysql_db);
        if (!$conn) {
            die("Database Connect Error: " . mysqli_connect_error());
        }
            
        //echo "Database Connected.<br><br>";
            
        $sql = "SELECT * FROM test_tb";
        $result = mysqli_query($conn$sql);
        
        if (mysqli_num_rows($result> 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data_array[] = $row;
            }
            $chart = json_encode($data_array);
        } else {
            echo "No Data";
        }
        
        //echo $chart;
 
        mysqli_close($conn);
    ?>
 
    <script type="text/javascript">
        google.charts.load('current', { packages: ['corechart''line'] });
        google.charts.load('current', { packages: ['table'] });
        google.charts.setOnLoadCallback(drawChart);
        
        function drawChart() {
            var chart_array = <?php echo $chart; ?>;
            //console.log(JSON.stringify(chart_array))
            var header = ['Date&Time(MM-DD HH:MM)''Temp''Humid'];
            var row = "";
            var rows = new Array();
            jQuery.each(chart_array, function(index, item) {
                row = [
                    item.dt.substr(511),  // 너무 긴 날짜 및 시간을 짧게 추출
                    Number(item.temp),
                    Number(item.humid)
                ];
                rows.push(row); 
            });
 
            var jsonData = [header].concat(rows);
            var data = new google.visualization.arrayToDataTable(jsonData);
 
            var lineChartOptions = {
                title: 'Temperaure & Humid',
                hAxis: {
                    title: 'Time',
                    showTextEvery: 4    // X축 레이블이 너무 많아 보기 힘드므로 4개마다 하나씩 표시
                },
                series: {
                    0: { targetAxisIndex: 0 },
                    1: { targetAxisIndex: 1 }
                },
                vAxes: {
                    0: {
                        title: 'Temperature',
                        viewWindow: { min: -30, max: 50 }
                    },
                    1: {
                        title: 'Humid',
                        viewWindow: { min: 30, max: 100 }
                    }
                }
                //,
                //curveType: 'function',
                //legend: { position: 'bottom' }
            };
 
            var lineChart = new google.visualization.LineChart(document.getElementById('lineChart_div'));
            lineChart.draw(data, lineChartOptions);
 
            // 테이블 차트
            var tableChartOptions = {
                showRowNumber: true,
                width: '40%',
                height: '20%'
            }
 
            var tableChart = new google.visualization.Table(document.getElementById('tableChart_div'));
            tableChart.draw(data, tableChartOptions);
        }
    </script>
</head>
<body>
    <div id="lineChart_div" style="width: 900px; height: 500px"></div>
    <div id="tableChart_div"></div>
</body>
</html>
 

 

소스를 수정하고 웹서버에 저장한다.(/var/www/html/index.php)

 

웹서버에 접속하면 위와 같은 그래프와 차트가 표시된다.

 

※ 참고

2022.05.05 - [Web Development] - Google Chart - 구글 차트 1

반응형
Posted by J-sean
:

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# WinForm과 SQLite를 이용해 간단한 회원관리 프로그램을 만들어 보자.

 

DataGridView, Button등을 윈폼에 적당히 배치한다.

 

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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Data.SQLite;
 
namespace Manager
{
    public partial class Form1 : Form
    {
        SQLiteConnection connection;
        SQLiteCommand command;
        DataTable dataTable;
 
        public Form1()
        {
            InitializeComponent();
 
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
 
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.Items.Add("아이디로");
            comboBox1.Items.Add("이름으로");
            comboBox1.Items.Add("생일로");
            comboBox1.SelectedIndex = 0;
 
            try
            {
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
 
                command = new SQLiteCommand(connection);
                command.CommandText = "CREATE TABLE IF NOT EXISTS member (" +
                    "id TEXT UNIQUE NOT NULL, " +
                    "name TEXT NOT NULL, " +
                    "birthday TEXT NOT NULL)";
                command.ExecuteNonQuery();
 
                command.CommandText = "SELECT * FROM member";
                SQLiteDataReader reader = command.ExecuteReader();
                dataTable = new DataTable();
                dataTable.Load(reader);
                dataGridView1.DataSource = dataTable;
                reader.Close();
 
                dataGridView1.Columns[0].HeaderText = "아이디";
                dataGridView1.Columns[1].HeaderText = "이름";
                dataGridView1.Columns[2].HeaderText = "생일";
 
                connection.Close();
 
                label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try // 회원 정보 수정
            {
                foreach (DataGridViewRow row in dataGridView1.Rows) // 아이디(변경불가 상황 가정)를 바꾸려 시도하는 경우 체크
                {
                    if (row.Cells[0].Value.ToString() == textBox1.Text.Trim()) // 아이디 비교
                    {
                        if (MessageBox.Show(row.Cells[1].Value + "의 데이터를 수정 합니다. 수정하시겠습니까?",
                            "수정", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                            connection.Open();
 
                            command = new SQLiteCommand(connection);
                            command.CommandText = "UPDATE member set name=:name, birthday=:birthday WHERE id=:id";
                            command.Parameters.Add("name", DbType.String).Value = textBox2.Text.Trim();
                            command.Parameters.Add("birthday", DbType.String).Value = textBox3.Text.Trim();
                            command.Parameters.Add("id", DbType.String).Value = textBox1.Text.Trim();
                            command.ExecuteNonQuery();
 
                            connection.Close();
 
                            row.Cells[0].Value = textBox1.Text.Trim();
                            row.Cells[1].Value = textBox2.Text.Trim();
                            row.Cells[2].Value = textBox3.Text.Trim();
 
                            return;
                        }
                        else
                        {
                            //MessageBox.Show("바뀌지 않았습니다.");
                            return;
                        }
                    }
                }
                MessageBox.Show(textBox1.Text + "는 존재하지 않는 ID 입니다.");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            // 프로그램 시작 시 인덱스 에러 방지
            if (dataGridView1.SelectedRows.Count < 1)
                return;
 
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            textBox1.Text = row.Cells[0].Value.ToString();
            textBox2.Text = row.Cells[1].Value.ToString();
            textBox3.Text = row.Cells[2].Value.ToString();
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            try // 회원 추가
            {
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
 
                command = new SQLiteCommand(connection);
                command.CommandText = $"INSERT INTO member (id, name, birthday) VALUES (" +
                    $"'{textBox1.Text.Trim()}', '{textBox2.Text.Trim()}', '{textBox3.Text.Trim()}')";
                command.ExecuteNonQuery();
 
                connection.Close();
 
                dataTable.Rows.Add(textBox1.Text.Trim(), textBox2.Text.Trim(), textBox3.Text.Trim());
                label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            try // 회원 삭제
            {
                if (MessageBox.Show($"{dataGridView1.SelectedRows[0].Cells[1].Value}의 데이터를 정말 삭제 하시겠습니까?",
                    "삭제", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                    connection.Open();
 
                    command = new SQLiteCommand(connection);
                    command.CommandText = "DELETE from member WHERE id=:id";
                    command.Parameters.Add("id", DbType.String).Value = textBox1.Text.Trim();
                    command.ExecuteNonQuery();
 
                    connection.Close();
 
                    DataGridViewRow row = dataGridView1.SelectedRows[0];
                    dataGridView1.Rows.Remove(row);
 
                    label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
                }
                else
                {
                    //MessageBox.Show("삭제하지 않았습니다");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            try // 검색
            {
                string filter;
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        filter = "id";
                        break;
 
                    case 1:
                        filter = "name";
                        break;
 
                    case 2:
                        filter = "birthday";
                        break;
 
                    default:
                        filter = "id";
                        break;
                }
 
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
                command = new SQLiteCommand(connection);
 
                if (textBox4.Text.Trim().Length == 0)
                {
                    command.CommandText = $"SELECT * FROM member";
                }
                else
                {
                    command.CommandText = $"SELECT * FROM member where {filter}='{textBox4.Text.Trim()}'";
                }
                SQLiteDataReader reader = command.ExecuteReader();
                dataTable = new DataTable();
                dataTable.Load(reader);
                dataGridView1.DataSource = dataTable;
                reader.Close();
 
                connection.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // 항목 번호 그리기
            String rowIndex = (e.RowIndex + 1).ToString();
 
            StringFormat centerFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
 
            Rectangle headerBound = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
                dataGridView1.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIndex, Font, SystemBrushes.ControlText, headerBound, centerFormat);
        }
    }
}
 

 

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

 

프로그램을 실행하면 빈 데이터베이스가 생성된다.

 

회원 추가, 수정, 삭제, 검색등을 해 본다.

 

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

C# WinForm의 DataGridView와 SQLite를 연동해 보자.

 

윈폼에 DataGridView를 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Data.SQLite;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            try
            {
                SQLiteConnection connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/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)";
                command.ExecuteNonQuery();
 
                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')";
                command.ExecuteNonQuery();
 
                command.CommandText = "SELECT * FROM test";
                SQLiteDataReader dataReader = command.ExecuteReader();
                DataTable dataTable = new DataTable();
                dataTable.Load(dataReader);
                dataGridView1.DataSource = dataTable;
                dataReader.Close();
 
                // 각 컬럼의 HeaderText를 변경하지 않으면 SQLite에 지정된 컬럼명 그대로 사용된다.
                dataGridView1.Columns[0].HeaderText = "아이디";
                dataGridView1.Columns[1].HeaderText = "이름";
                dataGridView1.Columns[2].HeaderText = "생일";
 
                connection.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        // DataGridView에 번호를 그려주는(DrawString) 함수.
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //DataGridView dataGridView = sender as DataGridView;
            // 'sender as DataGridView' 는 dataGridView1과 동일.
 
            String rowIndex = (e.RowIndex + 1).ToString();
            //String rowIdx = (e.RowIndex + 1).ToString("D4"); // 10진수 4자리 표기(0001~9999). 16진수4자리는 'X4'.
 
            StringFormat centerFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
 
            Rectangle headerBound = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
                dataGridView1.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIndex, Font, SystemBrushes.ControlText, headerBound, centerFormat);
        }
    }
}
 

 

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

 

실행하면 데이터가 표시된다.

 

반응형
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) 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
: