1. DB 접속 후, into ~ outfile 형식

SELECT order_id,product_name,qty 
FROM orders 
INTO OUTFILE '/tmp/orders.csv' 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n'


 * Access deniey 발생 시
 ERROR 1045 (28000): Access denied for user 'user1'@'localhost' (using password: YES)
 
 GRANT FILE ON *.* TO 'kccfres'@'localhost';
 
 
 * secure-file-priv 처리
 ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
 
 1. Mysql client 로 연결후 SHOW variable 로 MySQL 환경 변수 확인
   mysql> SHOW VARIABLES LIKE "secure_file_priv";
  +------------------+-----------------------+
  | Variable_name    | Value                 |
  +------------------+-----------------------+
  | secure_file_priv | /var/lib/mysql-files/ |
  +------------------+-----------------------+
  1 row in set (0.02 sec)

2. INTO OUTFILE 의 저장 경로를 위의 secure_file_priv 폴더로 변경
  INTO OUTFILE '/tmp/orders.csv' →  INTO OUTFILE '/var/lib/mysql-files/orders.csv' 
  
3. 쿼리 재실행

2. DB 접속하지 않은 상태에서 실행

mysql -user -pass -e "select cols from orders" dbname > /tmp/orders.csv

//리모트인 경우 
mysql -h {아이피} -user -pass -e "select cols from orders" dbname > /tmp/orders.csv

참고

https://www.lesstif.com/dbms/mysql-client-query-csv-text-54951965.html

https://xn--lg3bu39b.xn--mk1bu44c/77

1. 테이블 행(row) 클릭 시 해당 행의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>   
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
 
<body>  
    <br><br>
    <div class="row">
        <table id="example-table-1" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user01</td>
                    <td>홍길동</td>
                    <td>hong@gmail.com</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user02</td>
                    <td>김사부</td>
                    <td>kim@naver.com</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user03</td>
                    <td>존</td>
                    <td>John@gmail.com</td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex1_Result1" ></div> 
        <div class="col-lg-12" id="ex1_Result2" ></div> 
    </div>
    <br><br>     
</body>
</html>

javascript

<script>
    // 테이블의 Row 클릭시 값 가져오기
    $("#example-table-1 tr").click(function(){     
        var str = ""
        var tdArr = new Array();    // 배열 선언
            
        // 현재 클릭된 Row(<tr>)
        var tr = $(this);
        var td = tr.children();
            
        // tr.text()는 클릭된 Row 즉 tr에 있는 모든 값을 가져온다.
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
        // td.eq(index)를 통해 값을 가져올 수도 있다.
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
          
        $("#ex1_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex1_Result2").html(str);
    });    
</script>

2. 버튼 클릭 시 해당 행(row)의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> 
</head>
 
<body>   
    <br><br>
    <div class="row">
        <table id="example-table-2" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                    <th>버튼</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user04</td>
                    <td>맥크리</td>
                    <td>sunset@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user05</td>
                    <td>메르시</td>
                    <td>Mercy@naver.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user06</td>
                    <td>한조</td>
                    <td>trolling@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex2_Result1" ></div> 
        <div class="col-lg-12" id="ex2_Result2" ></div> 
    </div> 
    <br><br> 
</body>
</html>

javascript

<script>
    // 버튼 클릭시 Row 값 가져오기
    $(".checkBtn").click(function(){ 
            
        var str = ""
        var tdArr = new Array();    // 배열 선언
        var checkBtn = $(this);
            
        // checkBtn.parent() : checkBtn의 부모는 <td>이다.
        // checkBtn.parent().parent() : <td>의 부모이므로 <tr>이다.
        var tr = checkBtn.parent().parent();
        var td = tr.children();
            
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){    
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
 
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
            
        $("#ex2_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex2_Result2").html(str);    
    }); 
</script>

참고

https://all-record.tistory.com/172

html

<button id="my-btn" onclick="alert('클릭이벤트 발생')";>버튼</button>

js

//JQuery
$("#my-btn").trigger("click");

//javascript
document.getElementById("my-btn")[0].click();

참고

https://6developer.com/6

html에서 select2 id값을 설정

javascript에서 id값으로 html의 select2 값을 조회 및 변경

<!DOCTYPE html>
<html>
  <head>
    <title>Select2 Test</title>
    <!-- select2 css cdn -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <br />
    <div style="margin-left:10px;">
      <select class="form-control select2" id="search_type" name="search_type">
        <option value="all">ALL</option>
        <option value="sql">SQL</option>
        <option value="os">OS</option>
      </select>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <!-- select2 javascript cdn -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/js/select2.min.js"></script>
    <script>
    
      //Initialize Select2 Elements
      $('.select2').select2({
        theme: "bootstrap4",
        width: 'auto',
        dropdownAutoWidth: true
      })
      
      //select2 선택값 변경
      $('#search_type').val('OS');
      // 위 코드로 변경이 되지 않는 경우
      $('#search_type').val('OS').trigger('change');
       
    </script>
  </body>
</html>

Python flask

test edit : db 데이터 수정 이후, 실행 결과를 리턴

test list : db의 table 조회 이후, 여러 행을 리스트 형태로 리턴

test detail : db 데이터 조회 결과가 1건인 경우, json 형태로 리턴

from flask import render_template, request, flash, redirect, url_for, Blueprint, Markup, jsonify, session, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text, update
from sqlalchemy.exc import SQLAlchemyError

@bts_blueprint.route('test/edit', methods=['POST'])
def test_edit():

    print("## test_edit ##")

    try:
        # 처리 변수
        numId = request.form['id']
        strName = request.form['name']

        # 처리 로직
        sql = text('update tblTest set name = :strName where id = :numId')
        connection = db.session.connection()
        db.engine.execute(sql, numId=numId, strName=strName)
                
        return jsonify(message="Edit Success"), 200

    except (RuntimeError, TypeError, NameError, SQLAlchemyError) as e:
        print("#### Edit Failed !! " + str(e))
        db.session.rollback()

        return jsonify(message=str(e)), 1000
        
        
@bts_blueprint.route('test/list', methods=['POST'])
def test_list():

    print("## test_list ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c, d, e from tblTest where id > :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)
                
    return render_template('test.html', results=list(results))


@bts_blueprint.route('test/detail', methods=['POST'])
def test_detail():

    print("## test_detail ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c from tblTest where id = :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)

    if results != None:
        results_detail = {}
        for r in results:
            results_detail['a'] = r[0]
            results_detail['b'] = r[1]
            results_detail['c'] = r[2]
            
    return jsonify(results_detail=results_detail)

javascript

funtion test_edit()
{
    // Test edit
    $.ajax({
        url:'/test/edit',
        type:'POST',
        data: {id:id, name:name},
        success: function(data){
            //Success
            showAlert('Edit Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('Edit Fail...','', 4, 3000);
        }
    });
}


funtion test_list()
{
    // Test list
    $.ajax({
        url:'/test/list',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            for(var key in data){
                console.log(key, data[key]);
            }
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('list Fail...','', 4, 3000);
        }
    });
}


funtion test_detail()
{
    // Test detail
    $.ajax({
        url:'/test/detail',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            detail_a = data.results_detail.a
            detail_b = data.results_detail.b
            detail_c = data.results_detail.c
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('detail Fail...','', 4, 3000);
        }
    });
}

올해 01월 01일, 올해 12월 마지막일

//현재 시간
> var Nowdate = new Date()
> Nowdate 
Tue Jul 06 2021 23:36:20 GMT+0900 (한국 표준시)
//현재 년도
> FullYear = Nowdate.getFullYear()
2021
//현재 달
> Tmp_Month = Nowdate.getMonth()+1
7
> CurrentMonth = Tmp_Month >= 10 ? Tmp_Month : '0' + Tmp_Month
"07"
//마지막 달의 마지막 일
> (new Date(FullYear, 12, 0))
Fri Dec 31 2021 00:00:00 GMT+0900 (한국 표준시)
> (new Date(FullYear, 12, 0)).getDate()
31
// 올해 01월 01일
> FullYear + '-01-01 00:00:00'
"2021-01-01 00:00:00"
// 올해 12월 마지막일
> FullYear + '-12-' + LastDay + ' 23:59:59'
"2021-12-31 23:59:59"

일주일전

> var Nowdate = new Date()
> Nowdate
Tue Jul 06 2021 23:55:01 GMT+0900 (한국 표준시)
> var Agodate = new Date(Nowdate.getTime() - (7*24*60*60*1000))
//일주일전
> Agodate 
Tue Jun 29 2021 23:55:01 GMT+0900 (한국 표준시)

//현재 달
> var NowMonth = ((Nowdate.getMonth()+1) >= 10 ? (Nowdate.getMonth()+1) : '0' + (Nowdate.getMonth()+1))
"07"
//현재 일
> var NowDay = (Nowdate.getDate() >= 10 ? Nowdate.getDate() : '0' + Nowdate.getDate())
"06"
// 일주일전 달
> var AgoMonth = ((Agodate.getMonth()+1) >= 10 ? (Agodate.getMonth()+1) : '0' + (Agodate.getMonth()+1))
"06"
// 일주일전 일
> var AgoDay = (Agodate.getDate() >= 10 ? Agodate.getDate() : '0' + Agodate.getDate())
29

//현재 날짜
> Nowdate.getFullYear() + '-' + NowMonth + '-' + NowDay + ' 00:00:00'
"2021-07-06 00:00:00"

//일주일전 날짜
> Agodate.getFullYear() + '-' + AgoMonth + '-' + AgoDay + ' 00:00:00'
"2021-06-29 00:00:00"

1일 추가, 1시간 추가

//1일 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (24*60*60*1000))
1628348400000
> new Date(tmpdate)
Sun Aug 08 2021 00:00:00 GMT+0900 (한국 표준시)

//1시간 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (1*60*60*1000))
1628265600000
> new Date(tmpdate)
Sat Aug 07 2021 01:00:00 GMT+0900 (한국 표준시)

포멧 변경

function sDateToDate(strDate)
{
    //Ex) '04/26/2021 4:37 PM'
    var yyyyMMDD = String(strDate)
    var sYear = yyyyMMDD.substring(6,10);
    var sMonth = yyyyMMDD.substring(0,2);
    var sDate = yyyyMMDD.substring(3,5);
    var sTime = yyyyMMDD.substring(10,19);

    //Ex) '2021-04-26 4:37 PM'
    return sYear + '-' + sMonth + '-' + sDate + sTime
}

어제

from datetime import datetime, date, timedelta

yesterday = date.today() - timedelta(1)
yesterday_text = yesterday.strftime('%Y-%m-%d 00:00:00')

달의 첫번째 일

from datetime import datetime, date, timedelta
import calendar


now_date = datetime.datetime.now()
month_frist_text = now_date.replace(day = 1).strftime("%Y-%m-%d 00:00:00")

달의 마지막 일

from datetime import datetime, date, timedelta
import calendar

now_date = datetime.datetime.now()
month_last_text = now_date.replace(day = calendar.monthrange(now_date.year, now_date.month)[1]).strftime("%Y-%m-%d 23:59:59")

 

datetime모듈내의 클래스

클래스 내용
datetime.date 일반적으로 사용되는 그레고리안 달력(Gregorian Calendar)의 년, , 일을 나타냄
datetime.time 시간을 시, , , 마이크로초, 시간대(Time zone)로 나타냄
datetime.datetime date클래스와 time클래스의 조합으로 년, , , , , , 마이크로초, 시간대 정보를 나타냄
datetime.timedelta 두 날짜 혹은 시간 사이의 기간을 표현

datetime.date 클래스

datetime.date클래스는 일반적으로 사용되는 년, , 일로 표기되는 그레고리안 달력의 날짜를 표현함

생성자 : datetime.date(year, month, day)

숫자로 년, , 일을 입력받아서 date객체를 생성

- year : 1 ~ 9999

- month : 1 ~ 12

- day : 1 ~ 해당월의 마지막 날짜

>>> import datetime
>>> D=datetime.date(2013,2,18)
>>> D
datetime.date(2013, 2, 18)
>>> print(D)
2013-02-18
>>> D=datetime.date(2013,2,31) #해당월의 최대일수를 넘으면 ValueError발생
Traceback (most recent call last):
  File "<pyshell#194>", line 1, in <module>
    D=datetime.date(2013,2,31)
ValueError: day is out of range for month

datetime.date클래스 속성

속성 내용
year (읽기전용)
month (읽기전용)
day (읽기전용)
max date객체의 최댓값
(9999,12,31)
min date객체의 최솟값
(1,1,1)
>>> import datetime
>>> D=datetime.date(2013,2,18)
>>> D.year #년
2013
>>> D.month #월
2
>>> D.day #일
18
>>> D.max #date객체의 최댓값
datetime.date(9999, 12, 31)
>>> D.min #date객체의 최솟값
datetime.date(1, 1, 1)

today()

현재 시스템의 오늘 날짜 date객체를 반환

>>> import datetime
>>> datetime.date.today()
datetime.date(2013, 3, 29)

replace(year, month, day)

입력된 인자로 변경된 date객체를 반환, 원본객체는 변경되지 않음

변경하려는 속성만 명시적으로 전달할수 있음

>>> import datetime
>>> a=datetime.date.today()
>>> a
datetime.date(2013, 3, 29)
>>> b=a.replace(day=1) #a객체에서 day만 변경
>>> a
datetime.date(2013, 3, 29) #원본은 변경되지 않음
>>> b
datetime.date(2013, 3, 1)

weekday()

요일을 정수로 변환하여 반환

:0, :1, :2, :3, :4, :5, :6

>>> import datetime
>>> a=datetime.date.today()
>>> a.weekday()
4

isoformat()

date객체의 정보를 "YYYY-MM-DD"형태의 문자열로 반환

>>> import datetime
>>> D=datetime.date.today()
>>> D.isoformat()
'2013-03-29'

strftime(format)

지정된 포맷에 맞춰 datetime.date객체의 정보를 문자열로 반환

지시자 내용
%y 연도를 축약하여 표시('13')
%Y 연도를 축약하지 않고 표시('2013')
%b 축약된 월이름('Mar')
%B 축약되지 않은 월 이름('March')
%m 숫자로 표현한 월(01~12)
%d (01~31)
%H 24시를 기준 시(00~23)
%I(아이) 12시를 기준 시(01~12)
%M (00~59)
%S (00~61)
%p 오전(AM)/오후(PM) 표시 ('AM')
%a 축약된 요일 이름('Fri')
%A 축약되지 않은 요일이름('Friday')
%w 요일을 숫자로 표시
(:0, :1, :2, :3, :4, :5, :6)
%j 1 1일부터 누적된 날짜(001~366)

microsecond = %f

time모듈의 strftime메서드와 형식지시자가 같음

>>> import datetime
>>> D=datetime.date(2013,2,18)
>>> D.strftime('%Y %m %d')
'2013 02 18'
>>> D.strftime('%y/%m/%d %H:%M:%S') #시, 분, 초에 대한 정보는 없기때문에 '0'으로 반환됨
'13/02/18 00:00:00'

 

datetime.time클래스

time클래스는 시, , 초와 같은 시간을 표현함

생성자 : datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])

숫자로 시, , , 마이크로초, 시간대정보(Time Zone)을 입력받아서 time객체를 생성하며, 각 인자는 생략하거나 명시적으로 지정할수 있다.

- hour : 0 ~ 23

- minute : 0 ~ 59

- second : 0 ~ 59

- microsecond : 0 ~ 999999

>>> import datetime
>>> datetime.time(23) #시간만 입력
datetime.time(23, 0)
>>> datetime.time(23,15,45,2341) #시, 분, 초 마이크로초 입력
datetime.time(23, 15, 45, 2341)
>>> datetime.time(hour=23,second=5) #인자지정하여 입력
datetime.time(23, 0, 5)
>>> datetime.time(25) #인자허용값을 벗어난경우
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    time(25)
ValueError: hour must be in 0..23

datetime.time클래스 속성

속성 내용
hour (읽기전용)
minute (읽기전용)
second (읽기전용)
microsecond 마이크로초(읽기전용)
max time객체가 표현할수 있는 최댓값
(0,0,0,0)
min time객체가 표현할수 있는 최솟값
(23,59,59,999999)
>>> import datetime
>>> T=datetime.time(23,30,15,2904)
>>> T.hour #시
23
>>> T.minute #분
30
>>> T.second #초
15
>>> T.microsecond #마이크로초
2904
>>> T.max #time객체의 최댓값
datetime.time(23, 59, 59, 999999)
>>> T.min #time객체의 최솟값
datetime.time(0, 0)

isoformat()

time객체의 값을 "HH:MM:SS.mmmmmm'형식이나

'HH:MM:SS'형식(micro초가 없는경우)의 문자열을 반환

>>> import datetime
>>> T=datetime.time(23,30,15,3759)
>>> T.isoformat()
'23:30:15.003759'

strftime(format)

지정된 포맷에 맞춰 datetime.time객체의 정보를 문자열로 반환

지시자 내용
%y 연도를 축약하여 표시('13')
%Y 연도를 축약하지 않고 표시('2013')
%b 축약된 월이름('Mar')
%B 축약되지 않은 월 이름('March')
%m 숫자로 표현한 월(01~12)
%d (01~31)
%H 24시를 기준 시(00~23)
%I(아이) 12시를 기준 시(01~12)
%M (00~59)
%S (00~61)
%p 오전(AM)/오후(PM) 표시 ('AM')
%a 축약된 요일 이름('Fri')
%A 축약되지 않은 요일이름('Friday')
%w 요일을 숫자로 표시
(:0, :1, :2, :3, :4, :5, :6)
%j 1 1일부터 누적된 날짜(001~366)

time모듈의 strftime메서드와 형식지시자가 같음

>>> import datetime
>>> T=datetime.time(23,30,15,3759)
>>> T.strftime('%Y %m %d %H:%M:%S:')
'1900 01 01 23:30:15:'

datetime.datetime 클래스

datetime클래스는 date클래스와 time클래스의 조합으로 이루어져 있다.

생성자 : datetime.datetime(yesr, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

숫자로 각 인자를 받아서 datetime객체를 생성하며, , , 일은 생략이 불가하다.

명시적으로 인자를 지정하여 입력할수 있고, 생략된 인자는 0으로 초기화된다.

- year : 1 ~ 9999

- month : 1 ~ 12

- day : 1 ~ 해당월의 마지막 날짜

- hour : 0 ~ 23

- minute : 0 ~ 59

- second : 0 ~ 59

- microsecond : 0 ~ 999999

>>> import datetime
>>> datetime.datetime(2013,2,18) #년, 월, 일만 입력
datetime.datetime(2013, 2, 18, 0, 0)
>>> datetime.datetime(2013,2,hour=23,second=30,day=18) #명시적으로 인자를 지정
datetime.datetime(2013, 2, 18, 23, 0, 30)
>>> datetime.datetime(2013) #월,일인자가 생략되어 Error발생
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    datetime(2013)
TypeError: Required argument 'month' (pos 2) not found

datetime.datetime클래스 속성

속성 내용
year (읽기전용)
month (읽기전용)
day (읽기전용)
hour (읽기전용)
minute (읽기전용)
second (읽기전용)
microsecond 마이크로초(읽기전용)
max datetime객체가 표현할수 있는 최댓값
(9999,12,31,23,59,59,999999)
min datetime객체가 표현할수 있는 최솟값
(1,1,1)

datetime.datetime객체를 생성하는 클래스메서드

>today()

현재 LST 기준의datatime객체를 생성

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2013, 3, 29, 4, 30, 17, 967000)

now([tz])

현재 LST기준의 datetime객체를 생성

시간대 정보가 입력되지 않으면 플랫폼의 시간대를 그대로 사용

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2013, 3, 29, 4, 33, 3, 498000)

utcnow()

UTC기준의datetime객체를 생성

>>> import datetime
>>> datetime.datetime.utcnow()
datetime.datetime(2013, 3, 28, 19, 36, 38, 170000)

fromtimestamp(timestamp[,tz])

타임스탬프를 지방 기준의 datetime객체를 생성

>>> import datetime,time
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2013, 3, 29, 4, 43, 48, 201000)

utcfromtimestamp(timestamp)

타임스탬프를 UTC기준의 datetime객체를 생성

>>> import datetime,time
>>> datetime.datetime.utcfromtimestamp(time.time())
datetime.datetime(2013, 3, 28, 19, 44, 46, 358000)

strptime(date_string,format)

시간을 표현한 사용자가 정의한 형식문자열을 이용하여 datetime객체를 생성

지시자 내용
%y 연도를 축약하여 표시('13')
%Y 연도를 축약하지 않고 표시('2013')
%b 축약된 월이름('Mar')
%B 축약되지 않은 월 이름('March')
%m 숫자로 표현한 월(01~12)
%d (01~31)
%H 24시를 기준 시(00~23)
%I(아이) 12시를 기준 시(01~12)
%M (00~59)
%S (00~61)
%p 오전(AM)/오후(PM) 표시 ('AM')
%a 축약된 요일 이름('Fri')
%A 축약되지 않은 요일이름('Friday')
%w 요일을 숫자로 표시
(:0, :1, :2, :3, :4, :5, :6)
%j 1 1일부터 누적된 날짜(001~366)

time모듈의 strftime메서드와 형식지시자가 같음

>>> import datetime,time
>>> timestring=time.ctime(1234567890)
>>> timestring
'Sat Feb 14 08:31:30 2009'
>>> datetime.datetime.strptime(timestring,"%a %b %d %H:%M:%S %Y")
datetime.datetime(2009, 2, 14, 8, 31, 30)

date()

원본객체의 년, , 일 정보를 가지고 있는 date객체를 반환

>>> import datetime
>>> DT=datetime.datetime(2013,2,18,22,30,15)
>>> D=DT.date()
>>> D
datetime.date(2013, 2, 18)

time()

원본객체의 시, , , 마이크로초를 가지고 있는 time객체를 반환

>>> import datetime
>>> DT=datetime.datetime(2013,2,18,22,30,15)
>>> T=DT.time()
>>> T
datetime.time(22, 30, 15)

replace()

입력된 값으로 변경된 datetime객체를 반환, 원본객체는 변경되지 않음

>>> import datetime
>>> DT=datetime.datetime(2013,2,18,22,30,15)
>>> DT_1=DT.replace(year=1987)
>>> DT
datetime.datetime(2013, 2, 18, 22, 30, 15)
>>> DT_1
datetime.datetime(1987, 2, 18, 22, 30, 15)

isoformat()

datetime객체를 'YYYY-MM-DDTHH:MM:SS.mmmmmm'형식으로 변환하여 문자열로 반환

마이크로초가 0인경우 '.mmmmmm'부분은 생략됨

>>> import datetime
>>> DT=datetime.datetime.today()
>>> DT.isoformat()
'2013-03-29T07:57:58.014000'
>>> DT.replace(microsecond=0).isoformat() #마이크로초가 0인경우
'2013-03-29T07:57:58'

strftime(format)

지정된 포맷형식에 맞추어 datetime.datetime객체를 문자열로 반환

지시자 내용
%y 연도를 축약하여 표시('13')
%Y 연도를 축약하지 않고 표시('2013')
%b 축약된 월이름('Mar')
%B 축약되지 않은 월 이름('March')
%m 숫자로 표현한 월(01~12)
%d (01~31)
%H 24시를 기준 시(00~23)
%I(아이) 12시를 기준 시(01~12)
%M (00~59)
%S (00~61)
%p 오전(AM)/오후(PM) 표시 ('AM')
%a 축약된 요일 이름('Fri')
%A 축약되지 않은 요일이름('Friday')
%w 요일을 숫자로 표시
(:0, :1, :2, :3, :4, :5, :6)
%j 1 1일부터 누적된 날짜(001~366)

time모듈의 strftime메서드와 형식지시자가 같음

>>> import datetime
>>> DT=datetime.datetime.today()
>>> DT.strftime('%Y-%m-%d %H:%M:%S %a')
'2013-03-29 08:04:55 Fri'

datetime.timedelta

datetime.timedelta클래스는 두 날짜 혹은 시간 사이의 기간을 표현한다.

인자는 양수인경우 현시점으로부터 이후를 나타내며, 음수인경우 현시점 이전을 나타낸다.

생성자 : datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]])

>>> import datetime
>>> datetime.timedelta(days=-3) #3일 이전
datetime.timedelta(-3)
>>> datetime.timedelta(hours=7) #7시간 이후
datetime.timedelta(0, 25200)
>>> datetime.timedelta(weeks=2,days=3,hours=-3,minutes=30)
datetime.timedelta(16, 77400)
>>> datetime.timedelta(minutes=3,milliseconds=-20,microseconds=400)
datetime.timedelta(0, 179, 980400)

생성되는 timedelta객체의 값을 확인해보면 생성자에 전달된 값과 다른것을 알수 있다.

그 이유는 동일한 기간을 표현하는 방식이 다양하게 표현(1weeks 7days는 동일함)될수 있기 대문에, 입력된 값을 가지고 timedelta객체에서 정규화과정을 거쳐 유일한 표현방식으로 변경하기 때문이다.

정규화 결과 timedelta객체 저장되는 값은 아래와 같다.

- days : -999999999 ~ 999999999

- seconds : 0 ~ 86399(24시간을 초로 환산하면 86400)

- microseconds : 0 ~ 999999

그렇기 때문에 timedelta객체를 이용하여 표현할수 있는 가장 작은 값으 정규화과정을 거치면 아래와 같다.

>>> datetime.timedelta(microseconds=-1) #현재 이전으로 가장 작은값
datetime.timedelta(-1, 86399, 999999)
>>> datetime.timedelta(microseconds=1) #현재 이후로 가장 작은값
datetime.timedelta(0, 0, 1)

시간, 날짜의 연산

생성된 timedelta클래스객체를 이용하여 아래의 연산을 수행할수 있다.

연산결과로는 모두 timedelta객체가 반환된다.

- timedelta_3 = timedelta_1 + timedelta_2

- timedelta_3 = timedelta_1 - timedelta_2

- timedelta_3 = timedelta_1 * int = int * timedelta_1

- timedelta_2 = timedelta_1 // int

- abs(timedelta)

>>> from datetime import timedelta
>>> td_1 = timedelta(hours=7) #현재로부터 7시간 이후
>>> td_2 = timedelta(days=-3) #현재로부터 3일 이전
>>> td_1 + td_2 #두 timedelta의 합
datetime.timedelta(-3, 25200) #7시간 = 25200초
>>> td_1 - td_2 #두 timedelta의 차
datetime.timedelta(3, 25200)
>>> td_1 * 4 #timedelta와 정수의 곱
datetime.timedelta(1, 14400) #28시간 = 1일4시간 = 1일14400초
>>> td_1 // 3 #25200초 // 3
datetime.timedelta(0, 8400)
>>> abs(td_2) #기간의 절대값
datetime.timedelta(3)

비교 연산

>>> from datetime import timedelta
>>> td_1 = timedelta(hours=7)
>>> td_2 = timedelta(days=-3)
>>> td_1 > td_2
True
>>> td_1 < td_2
False
>>> td_1 = timedelta(hours=24) #24시간 = 86400초
>>> td_2 = timedelta(seconds=86400)
>>> td_1 == td_2
True

생성된 timedelta객체를 이용하여 date, datetime객체를 변경할수 있다. 지원하는 연산은 아래와 같으며, 각 객체간의 비교연산도 가능하다.

- date_2 = date_1 + timedelta

- date_2 = date_1 - timedelta

- timedelta = date_2 - date_1

- datetime_2 = datetime_1 + timedelta

- datetime_2 = datetime_1 - timedelta

- timedelta = datetime_1 - datetime_2

>>> from datetime import timedelta, date
>>> d = date.today()
>>> d
datetime.date(2013, 3, 29)
>>> td=timedelta(days=3) #timedelta를 3일로 설정
>>> d + td #오늘로부터 3일 후
datetime.date(2013, 4, 1)
>>> d - td #오늘로부터 3일 전
datetime.date(2013, 3, 26)

 date객체 사이의 기간(timedelta)을 구하기 위해서는 아래와 같이 '-'연산으로 측정가능하며, date객체간의 비교연산도 가능하다.

>>> from datetime import timedelta, date
>>> d = date.today()
>>> d2 = d.replace(day=20)
>>> d2
datetime.date(2013, 3, 20)
>>> dt = d - d2
>>> dt
datetime.timedelta(9)
>>> d2 > d
False

아래는datetime객체와 관련된 연산의 예제이다

date객체가 지원하는 모든연산이 가능하다.

>>> import datetime
>>> dt=datetime.datetime.today()
>>> dt
datetime.datetime(2013, 4, 1, 23, 41, 52, 154000)
>>> td=datetime.timedelta(days=2,hours=2) #2일 2시간
>>> dt + td #datetime객체에서 timedelta(2일 2시간)을 더함
datetime.datetime(2013, 4, 4, 1, 41, 52, 154000)
>>> dt - td #datetime객체에서 timedelta(2일 2시간)을 뺌
datetime.datetime(2013, 3, 30, 21, 41, 52, 154000)
>>> dt2 = dt.replace(month=1, day=4, hour=7) #dt 객체의 값중 월, 일, 시간을 변경
>>> dt2
datetime.datetime(2013, 1, 4, 7, 41, 52, 154000)
>>> dt- dt2 #datetime객체간의 기간
datetime.timedelta(87, 57600)
>>> dt > dt2 #비교연산
True

참고

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=dudwo567890&logNo=130165166038

 

Python,module datetime [날짜시간]

-. datetime모듈내의 클래스 클래스 내용 datetime.date 일반적으로 사용되는 그레고리안 달력(Gregorian ...

blog.naver.com

설명

아래 값을 모두 변경하여도 SQL Server 카운트가 보이지 않는 경우 ... SQL Server를 재시작

SQL Server 재시작에도 보이지 않는 경우 OS 재시작

 

 

1.레지스트리에서 Disable Performance Counters  값 변경 : 1 -> 0

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\Disable Performance Counters

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLSERVER\Performance\Disable Performance Counters

 

2. services.msc에 Remote Registry가 시작되었는지 체크
 
3. unlodctr 와 lodctr 을 이용해서 SQL 관련 카운터를 다시 등록할것

1) cmd(Administrator권한으로)

2) SQL SERVER의 binn폴더로 이동

3)unlodctr을 이용해서 SQL counters를 unload한다.
    e.g. unlodctr MSSQLSERVER (for default instance)
    e.g. unlodctr SQLSERVERAGENT (for default SQL Agent)
    e.g. unlodctr MSSQL$TEST (for named instance)
    e.g. unlodctr SQLAGENT$TEST (for SQL agent)

4)lodctr을 이용해서 SQL counters를 다시 등록한다.
    e.g. lodctr perf-MSSQLSERVERsqlctr.ini (for default instance)
    e.g. lodctr perf-SQLSERVERAGENTsqlagtctr.ini (for default SQL Agent)
    e.g. lodctr perf-MSSQL$TESTsqlctr.ini (for named instance)
    e.g. lodctr perf-SQLAGENT$TESTsqlagtctr.ini (for SQL Agent)

5)Remote Registry service를 다시 시작한다.
    net stop "Remote Registry" 
    net start "Remote Registry"

6)필요할 경우 WMI와 WinPrivSE.exe 싱크를 다시 맞춘다.
    e.g. winmgmt /resyncperfctr "5660" 
   cf)5660은 WinPrivSE.exe 의 pid

4. performance counter를 재등록 한다.

lodctr /R --> 모든 
주의!!! 모든 performance counter registry 세팅을 재등록하게 된다.

참고

https://www.travisgan.com/2013/05/missing-sql-performance-counters.html

 

Missing SQL Performance Counters

Travis Gan's technical blog on Microsoft SQL Server, BI Stack (SSIS, SSRS, SSAS), Microsoft .NET and other technologies.

www.travisgan.com

 

Version - 5.7

-- 계정 생성

insert into user(host, user, authentication_string, ssl_cipher, x509_issuer, x509_subject)
values('%', 'account_srv', password('StrongPassword'), '', '', '');

--권한
grant all privileges on *.* to 'account_srv'@'%' identified by 'StrongPassword' with grant option;
grant select, insert, update, delete, execute on *.* to 'account_srv'@'%' identified by 'StrongPassword' with grant option;

flush privileges;

--- 비밀 번호 변경
UPDATE mysql.user SET Password=PASSWORD('StrongPassword') WHERE User='account_srv' AND Host='%';

SET PASSWORD FOR 'account_srv'@'%' = PASSWORD('StrongPassword');

ALTER USER 'account_srv'@'%' identified by 'StrongPassword';

flush privileges;

-- 권한 확인
# show grants for 'user'@'접속위치';
show grants for 'account_srv'@'%';

-- 계정 삭제
# drop user '계정아이디'@'접속위치';
drop user 'account_srv'@'%';

-- 권한 삭제
# revoke all on DB이름.테이블 FROM '계정아이디'@'접속위치';
revoke all on *.* FROM 'account_srv'@'%';

Version - 8.0

-- 사용자 정보 조회 
SELECT user,authentication_string,plugin,host FROM mysql.user; 

-- 사용자 생성 
create user 'account_srv'@'%' identified by 'StrongPassword'; 

-- 권한 부여 
GRANT ALL PRIVILEGES ON *.* TO 'account_srv'@'%'; 
GRANT GRANT OPTION ON *.* TO 'account_srv'@'%'; 

-- 비밀번호 plugin 변경 
ALTER USER 'account_srv'@'%' IDENTIFIED WITH mysql_native_password BY 'StrongPassword';

to Top