Sharing IT Knowledge and Life – Chia sẻ kiến thức IT và đời sống

Showing posts with label Databases. Show all posts
Showing posts with label Databases. Show all posts

Sunday, May 26, 2019

Oracle SQL căn bản P2


1> Execute a function that is defined in a package

Question: How can I execute a function that is defined in a package using Oracle/PLSQL?
Answer: To execute a function that is defined in a package, you'll have to prefix the function name with the package name.
package_name.function_name (parameter1, parameter2, ... parameter_n)
You can execute a function a few different ways.

Monday, September 3, 2018

Database normalization Introduction

Database normalization is the process of restructuring a relational database in accordance with a series of so-called normal forms in order to reduce data redundancyand improve data integrity. It was first proposed by Edgar F. Codd as an integral part of his relational model.
Normalization entails organizing the columns (attributes) and tables (relations) of a database to ensure that their dependencies are properly enforced by database integrity constraints. It is accomplished by applying some formal rules either by a process of synthesis (creating a new database design) or decomposition (improving an existing database design).
=> quá trình chuẩn hóa DB sẽ áp dụng 1 số luật (các dạng chuẩn) để thiết kế các bảng cơ sở dữ liệu sao cho có thể giảm thiếu tối đa dư thừa dữ liệu, sự chính xác của truy vấn dữ liệu, tăng performance truy xuất DB,..

Friday, April 13, 2018

LEFT JOIN vs. LEFT OUTER JOIN in SQL

As per the documentation: FROM (Transact-SQL):
<join_type> ::= 
    [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
    JOIN
The keyword OUTER is marked as optional (enclosed in square brackets), and what this means in this case is that whether you specify it or not makes no difference. Note that while the other elements of the join clause is also marked as optional, leaving them out will of course make a difference.
For instance, the entire type-part of the JOIN clause is optional, in which case the default is INNER if you just specify JOIN. In other words, this is legal:
SELECT *
FROM A JOIN B ON A.X = B.Y
Here's a list of equivalent syntaxes:
A LEFT JOIN B            A LEFT OUTER JOIN B
A RIGHT JOIN B           A RIGHT OUTER JOIN B
A FULL JOIN B            A FULL OUTER JOIN B
A INNER JOIN B           A JOIN B

Sunday, July 23, 2017

JPA Select Statements and NamedQuery

Select Statements

A select query has six clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. The SELECT and FROM clauses are required, but the WHERE, GROUP BY, HAVING, and ORDER BY clauses are optional. Here is the high-level BNF syntax of a query language select query:
     Note: some of the terms referred to in this chapter.
  • Abstract schema: The persistent schema abstraction (persistent entities, their state, and their relationships) over which queries operate. The query language translates queries over this persistent schema abstraction into queries that are executed over the database schema to which entities are mapped.
  • Abstract schema type: The type to which the persistent property of an entity evaluates in the abstract schema. That is, each persistent field or property in an entity has a corresponding state field of the same type in the abstract schema. The abstract schema type of an entity is derived from the entity class and the metadata information provided by Java language annotations.
  • Backus-Naur Form (BNF): A notation that describes the syntax of high-level languages. The syntax diagrams in this chapter are in BNF notation.
  • Navigation: The traversal of relationships in a query language expression. The navigation operator is a period.
  • Path expression: An expression that navigates to an entity's state or relationship field.
  • State field: A persistent field of an entity.
  • Relationship field: A persistent field of an entity whose type is the abstract schema type of the related entity.
QL_statement ::= select_clause from_clause 
  [where_clause][groupby_clause][having_clause][orderby_clause]

Ordinary JPA Query API

Queries are represented in JPA 2 by two interfaces - the old Query interface, which was the only interface available for representing queries in JPA 1, and the new TypedQuery interface that was introduced in JPA 2. The TypedQuery interface extends the Query interface.
In JPA 2 the Query interface should be used mainly when the query result type is unknown or when a query returns polymorphic results and the lowest known common denominator of all the result objects is Object. When a more specific result type is expected queries should usually use the TypedQuery interface. It is easier to run queries and process the query results in a type safe manner when using the TypedQuery interface.
Ngoài query thông thường dùng Query hoặc TypedQuery thì còn có JPA Criteria API  và named queries 

Building Queries with createQuery

As with most other operations in JPA, using queries starts with an EntityManager (represented by em in the following code snippets), which serves as a factory for both Query and TypedQuery:
  Query q1 = em.createQuery("SELECT c FROM Country c");
 
  TypedQuery<Country> q2 =
      em.createQuery("SELECT c FROM Country c", Country.class);

Friday, October 7, 2016

Đọc, xuất XLS,XLSX,CSV file trong Java

Một số khái niệm:

JExcelAPI, which is a mature, Java-based open source library that lets you read, write, and modify Excel spreadsheets. JExcelAPI's jexcelapi home directory contains a jxl.jar file that contains demos for reading, writing, and copying spreadsheets.
jXLS 1.x provides jxls-reader module to read XLS files and populate Java beans with spreadsheet data.
Jxls v2.x tương tự jXLS 1.x  nhưng đã có nhiều đặc tính mà phiên bản 1.x không có.
HSSF (Horrible SpreadSheet Format) – Use to read and write Microsoft Excel '97(-2007) (XLS) format files.
XSSF (XML SpreadSheet Format) – Used to reading and writting Excel 2007 OOXML - Open Office XML (.xlsx) format files.
SXSSF (package: org.apache.poi.xssf.streaming) is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document. Older rows that are no longer in the window become inaccessible, as they are written to the disk.
HWPF (Horrible Word Processor Format) – to read and write Microsoft Word 97 (DOC) format files.
HSMF (Horrible Stupid Mail Format) – pure Java implementation for Microsoft Outlook MSG files
HDGF (Horrible DiaGram Format) – One of the first pure Java implementation for Microsoft Visio binary files.  
HPSF (Horrible Property Set Format) – For reading “Document Summary” information from Microsoft Office files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HPBF (Horrible PuBlisher Format) – Apache's pure Java implementation for Microsoft Publisher files.
DDF (Dreadful Drawing Format) – Apache POI package for decoding the Microsoft Office Drawing format.
Opencsv is a very simple csv (comma-separated values) parser library for Java. It can dump out SQL tables to CSV:
     java.sql.ResultSet myResultSet = ....
     writer.writeAll(myResultSet, includeHeaders);
and It can bind CSV file to a list of Javabeans using CsvToBean, ColumnPositionMappingStrategy, HeaderColumnNameMappingStrategy classes.
Jasperreport java & JFrame VN apps

Các ví dụ:

Ví dụ dùng thư viện jxl:
WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setEncoding("UTF-8");
        Workbook workbookTemplate = null;
        workbookTemplate = Workbook.getWorkbook(new File(templateRealPath), wbSettings);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableWorkbook copy = Workbook.createWorkbook(outputStream, workbookTemplate);
        workbookTemplate.close();
        WritableSheet sheet = copy.getSheet(0);
        sheet.setName(sheetName);
.....
copy.write(); // Writes out the data held in this workbook in Excel format, to outputStream
        copy.close();       
        OutputStream os = new BufferedOutputStream(new FileOutputStream(realPath));
        outputStream.writeTo(os);
        outputStream.close();

Ví dụ dùng thư viện jxls 1.x:
package jxls.example;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import net.sf.jxls.transformer.XLSTransformer;

/**
 *
 * @author 
 */
public class EmployeeEx {

    public static void main(String[] args) throws Exception {
        Collection staff = new HashSet();
        staff.add(new Employee("Derek", 35, 3000, 0.30));
        staff.add(new Employee("Elsa", 28, 1500, 0.15));
        Map beans = new HashMap();
        beans.put("employee", staff);
        XLSTransformer transformer = new XLSTransformer();
        transformer.transformXLS("employeeTemplate.xls", beans, "employeeOut.xls");
    }
}

Tham khảo:

Apache POI Quick Guide

Sunday, August 28, 2016

Oracle SQL căn bản P1

Oracle/PLSQL FUNCTION

.1> REPLACE Function
Description
The Oracle/PLSQL REPLACE function replaces a sequence of characters in a string with another set of characters.

Syntax
REPLACE( string1_source, string_to_replace_source [, replacement_string_new_replace] )
ví dụ:
REPLACE('123123tech', '123');
Result: 'tech'

.2> Các hàm thống kê, ngày tháng, number, chuỗi

.3> INSTR ()

Hàm INSTR trả về vị trí của một chuỗi con trong một chuỗi cho trước.
Cú pháp:
INSTR( p_string, p_substring [, p_start_position [,  p_occurrence ] ] )
INSTR( string, substring [, start_position [, th_appearance ] ] )
Với 'th_appearance' là lần xuất hiện thứ th_appearance của substring, ngầm định là 1
ví dụ:
INSTR('Tech on the net', 'e')
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 1)
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 2)
Result: 11  (the second occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 3)
Result: 14  (the third occurrence of 'e')

INSTR('Tech on the net', 'e', -3, 2)
Result: 2

.4 substr
The Oracle/PLSQL SUBSTR functions allows you to extract a substring from a string.
The syntax for the SUBSTR function in Oracle/PLSQL is:
SUBSTR( string, start_position [, length ] )
For example:
SUBSTR('This is a test', 6, 2)
Result: 'is'

SUBSTR('This is a test', 6)
Result: 'is a test'
Hàm mở rộng của SUBSTR là REGEXP_SUBSTR có cú pháp như sau:

Chi tiết:

REGEXP_SUBSTR( string, pattern [, start_position [, nth_appearance [, match_parameter [, sub_expression ] ] ] ] )
chú ý: 
[^ ]Used to specify a nonmatching list where you are trying to match any character except for the ones in the lis
Ví dụ:
SELECT REGEXP_SUBSTR ('TechOnTheNet is a great resource', '(\S*)(\s)', 1, 1)
FROM dual;

Result: 'TechOnTheNet '
SELECT REGEXP_SUBSTR ('TechOnTheNet is a great resource', '(\S*)(\s)', 1, 2)
FROM dual;

Result: 'is '

select regexp_substr('2234,5678','[^,]+', 1, level)
          from dual
          connect by regexp_substr('2234,5678','[^,]+', 1, level) is not null;

Result: '2234'
        '5678'
Những ví dụ trên đã gọi hàm REGEXP_SUBSTR( string, pattern [, start_position [, nth_appearance ] ] )

ví dụ khác:
-- có rCodes = '22er,1123,fecb,mnpq'
 select regexp_substr(rCodes,'[^,]+', 1, level) LCODE
                                    from dual
                                    connect BY regexp_substr(rCodes, '[^,]+', 1, level)
                                    is not null) ;
sẽ trả về các bản ghi
LCODE
---------
22er
1123
fecb
mnpq


.5 Hàm NVL
The Oracle/PLSQL NVL function lets you substitute a value when a null value is encountered.
The syntax for the NVL function in Oracle/PLSQL is:
NVL( string1, replace_with )
For example:
SELECT NVL(supplier_city, 'n/a')
FROM suppliers;
The SQL statement above would return 'n/a' if the supplier_city field contained a null value. Otherwise, it would return the supplier_city value.
.6 Hàm NLSSORT
NLSSORT returns the string of bytes used to sort char.
Ví dụ:
select * from TABLE1 order by nlssort(ename,'nls_sort=vietnamese')
VIETNAM collation:
CREATE INDEX emp_idx1 ON emp(NLSSORT(ename, 'NLS_SORT=Vietnamese'));

.7 Hàm to_date
In Oracle, TO_DATE function converts a string value to DATE data type value using the specified format. In SQL Server, you can use CONVERT or TRY_CONVERT function with an appropriate datetime style.
-- Specify a datetime string and its exact format
  SELECT TO_DATE('2012-06-05', 'YYYY-MM-DD') FROM dual;

.8 Hàm TRUNC
The syntax for the TRUNC function in Oracle/PLSQL is:
TRUNC ( date [, format ]
Ví dụ: SELECT TRUNC(sysdate,'MM') FROM dual; -- trả về 9/1/2016
SELECT TRUNC(TO_DATE('22-SEP-2016'),'MM') FROM dual; -- trả về 9/1/2016
SELECT TRUNC(TO_DATE('22-SEP-2016')) FROM dual; -- trả về 0 giờ, 0 phút, 0 giây ngày 9/22/2016

.9 Hàm DECODE
The syntax for the DECODE function in Oracle/PLSQL is:
DECODE( expression , search , result [, search , result]... [, default] )
Parameters or Arguments
expression
The value to compare.
search
The value that is compared against expression.
result
The value returned, if expression is equal to search.
default
Optional. If no matches are found, the DECODE function will returndefault. If default is omitted, then the DECODE function will return null (if no matches are found).
Example
The DECODE function can be used in Oracle/PLSQL.
You could use the DECODE function in a SQL statement as follows:
SELECT supplier_name,
DECODE(supplier_id, 10000, 'IBM',
                    10001, 'Microsoft',
                    10002, 'Hewlett Packard',
                    'Gateway') result
FROM suppliers;
The above DECODE statement is equivalent to the following IF-THEN-ELSE statement:
IF supplier_id = 10000 THEN
   result := 'IBM';

ELSIF supplier_id = 10001 THEN
   result := 'Microsoft';

ELSIF supplier_id = 10002 THEN
   result := 'Hewlett Packard';

ELSE
   result := 'Gateway';

END IF;

The DECODE function will compare each supplier_id value, one by one.

.10 Hàm WM_CONCAT
WM_CONCAT is an undocumented function and as such is not supported by Oracle for user applications (MOS Note ID 1336219.1). Also, WM_CONCAT has been removed from 12c onward, so you can't pick this option.
It let you aggregate data from a number of rows into a single row, giving a list of data associated with a specific value. Using the SCOTT.EMP table as an example, we might want to retrieve a list of employees for each department.
Base Data:

    DEPTNO ENAME
---------- ----------
        20 SMITH
        30 ALLEN
        30 WARD
        20 JONES
        30 MARTIN
        30 BLAKE
        10 CLARK
        20 SCOTT
        10 KING
        30 TURNER
        20 ADAMS
        30 JAMES
        20 FORD
        10 MILLER

Desired Output:

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 SMITH,FORD,ADAMS,SCOTT,JONES
        30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD
If you are not running 11g Release 2 or above, but are running a version of the database where the WM_CONCAT function is present, then it is a zero effort solution as it performs the aggregation for you:
COLUMN employees FORMAT A50

SELECT deptno, wm_concat(ename) AS employees
FROM   emp
GROUP BY deptno;

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 SMITH,FORD,ADAMS,SCOTT,JONES
        30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD

3 rows selected.
Description
REGEXP_LIKE return boolean value ofregular expression matching in the WHERE clause.

Syntax
REGEXP_LIKE ( expression, pattern [, match_parameter ] )
ví dụ:
select rowid, REGISTER_NUMBER from document WHERE REGISTER_NUMBER is not null and  regexp_like(REGISTER_NUMBER, '^[0-9]+$');
SELECT rowid, (case when Not regexp_like(d.register_number, '^[0-9]+[0-9+-.\s]*$') then 0 else to_number(d.register_number) end) reg FROM document d order by reg desc;

Một số câu lệnh Oracle căn bản

  • select substr(txt, instr(txt, ',', 1, level) + 1,  instr(txt, ',', 1, level + 1) -instr(txt, ',', 1, level) -1) as token  from  (select ',' || '?' || ',' txt  from dual ) connect by level < length(txt) -length(replace(txt, ',', ''));
    => Kết quả:
    1 ?
  • select ',aa,bb,' || 'cc,dd' || ',' txt  from dual;
  • select  level from    dual connect by level <= 10;
  • ALTER TABLE fee_invoice ADD (id  NUMBER(15,0));
  • ALTER TABLE fee_invoice ADD PRIMARY KEY (id)
  • ALTER TABLE staff_abc ADD PRIMARY KEY (abc_code,staff_abc_code)
  • ALTER TABLE staff_abc ADD CONSTRAINT staff_abc_pk PRIMARY KEY (abc_code,staff_abc_code);
  • ALTER TABLE supplier DROP CONSTRAINT supplier_pk;
  • ALTER TABLE stock_daily_record ADD CONSTRAINT fk_stock_daily_record FOREIGN KEY (STOCK_ID) REFERENCES stock(STOCK_ID); 
  • ESCAPE in LIKE Conditions:
    The syntax for the LIKE condition in SQL is:
    expression LIKE pattern [ ESCAPE 'escape_character' ]
    Parameters or Arguments
    expression
    A character expression such as a column or field.
    pattern
    A character expression that contains pattern matching. The wildcards that you can choose from are:
    WildcardExplanation
    %Allows you to match any string of any length (including zero length)
    _Allows you to match on a single character
    ESCAPE 'escape_character'
    Optional. It allows you to pattern match on literal instances of a wildcard character such as % or _.
    For example:
    SELECT *
    FROM suppliers
    WHERE supplier_name LIKE 'Water!%' ESCAPE '!';
    This Oracle LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is Water%.
    SELECT last_name 
       FROM employees
       WHERE last_name 
       LIKE '%A\_B%' ESCAPE '\'; => '_' sẽ là ký tự literal.
    select * from shop s where s.shop_path like '%_$$1234%'   escape  '$'; => chứa 1 ký tự $
    select * from shop s where s.shop_path like '%_$\_1234%'   escape  '\';
    
  • IN, ANY, ALL, EXISTS
    Toán tử ANY chỉ ra bất kỳ giá trị liệt kê trong danh sách. ALL là tất cả các giá trị trong danh sách. EXISTS là tồn tại 1 bản ghi trả về trong câu truy vấn.
  • từ khóa HAVING: sẽ lọc kết quả truy vấn để lấy về 1 kết quả như mong muốn.
  • Kết nối các bảng csdl: join (inner join), left join, right join, full join
  • câu lệnh SELECT gồm những phép toán sau:
    >>Phép chiếu (Prjection): chỉ ra những column trong table muốn lấy data
    >>Phép chọn (Selection): lọc số lượng dòng dữ liệu cần lấy về từ 1 bảng
    >>Phép liên kết bảng (JOIN): lấy dữ liệu từ nhiều table thông qua kết nối các table với nhau bằng từ khóa join, left join, right join, full join
  • Hierarchical Queries



    Cú pháp:

    SELECT [COLUMNS]
    
    FROM TABLE_NAME
    
    START WITH [COLUMN] = [ROOT NODE VALUE]
    
    CONNECT BY [CONDITION]

    Ví dụ:

    Let’s analyze it: the CONNECT BY clause, mandatory to make a hierarchical query, is used to define how each record is connected to the hierarchical superior.
    The father of the record having MGR=x has EMPNO=x.
    On the other hand, given a record with EMPNO=x, all the records having MGR=x are his sons.
    The unary operator PRIOR indicates “the father of”.
    START WITH clause is used to from which records we want to start the hierarchy, in our example we want to start from the root of the hierarchy, the employee that has no manager.
    The root of the hierarchy could be not unique. In this example it is.
    The LEVEL pseudocolumn indicates at which level each record stays in the hierarchy, starting from the root that has level=1.
    connect by level là vị trí trong hệ thống phân cấp của bản ghi hiện hành trong mối qua hệ với nút gốc (root node). Nó cũng đặc tả mối quan hệ giữa parent rows và child rows của hệ thống phân cấp các bản ghi do có cột này là parent của cột kia trong 1 bảng CSDL. => level cũng sẽ giới hạn số dòng trả về, ví dụ: bằng số INPUT truyền vào.

Một số khái niệm RDBMS

PL/SQL trong oracle  là Procedural Language/Structured Query Language, tương đương với một ngôn ngữ lập trình hướng thủ tục được áp dụng trong oracle để viết ra các function/procedure thay vì sử dụng các câu truy vấn DB thông thường.
Function: trả về giá trị, về căn bản sẽ không có tham số kiểu OUT or IN OUT
Procedure: tương thự hàm void trong java, không trả về giá trị, nhưng lại có tham số kiểu OUT hoặc INOUT tương đương với trị trả về.
Hình sau nếu rõ Cấu trúc căn bản của khối lệnh PL/SQL:

DDL = data definition language, to create a database schema with CREATE and ALTER statements, creating tables, indexes, sequences, .. it is used to define data structures.
DML = data manipulation language to manipulate and retrieve data (insertions, updates, and deletions, retrieve data by executing queries with restrictions, projections, and join operations (including the Cartesian product). For  reporting, use SQL to group, order, and aggregate data as necessary; nest SQL statements inside each other (subselects)

Vendor Support for Catalog and Schema Objects
VendorCatalogSchema
OracleDoes not support catalogs. When specifying database objects, the catalog field should be left blank.Typically the name of an Oracle user ID.
  • server instance == database == catalog == all data managed by same execution engine
  • schema == namespace within database, identical to user account
  • user == schema owner == named account, identical to schema, who can connect to database, who owns the schema and use objects possibly in other schemas to identify any object you need (schema name + object name)


MySql căn bản

1. Tạo cơ sở dữ liệu MySQL

create database  struts2_db;
grant all on struts2_db.* to 'root'@'127.0.0.1' identified by '123456';
grant all on struts2_db.* to 'root'@'localhost' identified by '123456';
------------
grant all on *.* to 'root'@'192.168.1.132' identified by '123456';
mysql -h127.0.0.1 -uroot -p123456 < data.sql;
-------
grant all on struts2_db.* to 'root'@'localhost' identified by '123456';
grant all on struts2_db.* to 'root'@'127.0.0.1' identified by '123456';
2. Một vài Mysql command:
  • mysql -uroot -pexo
  • shell> mysql -u root
  • mysql> UPDATE mysql.user SET Password = PASSWORD('nbuser') WHERE User = 'root';
  • mysql> FLUSH PRIVILEGES;
  • sudo chmod 777 -R /var/lib/mysql/
  • grant all privileges on test2.* to gtest@"localhost" identified by 'gtest00'
  • ALTER TABLE t_pdata ADD is_sales int(11) DEFAULT '0'
  • mysqladmin -uroot -pexo variables | grep dir
  • ll /var/lib/mysql/ -tr
=> see the changes in mysql to know a mysql command running or not.
  • ps ax|grep mysql => to see mysql processes detail
  • ls /var/lib/mysql/plf_jcr/
  • enable or disable the general query log mysql to show low query
    mysql -uroot -pgtngtn -e "set global general_log_file='/var/lib/mysql/all.log'; set global general_log='ON'; "
    mysql -uroot -pexo -e "set global general_log_file='/var/lib/mysql/all.log'; set global general_log='ON';"
  • Login to mysql by command:
    mysql -uroot -pexo
  • CREATE INDEX IDX_NAME ON affablebean.product (name);
  • SELECT * FROM affablebean.product  prod where ID in ('5074','30','2552') ORDER BY FIELD(prod.ID,'5074','30','2552');
  • SELECT s.PROJECT_ID,t.TASK_ID,t.TITLE FROM plf_jcr.TASK_TASKS t inner join plf_jcr.TASK_STATUS s on t.STATUS_ID = s.STATUS_ID where s.PROJECT_ID in (SELECT PROJECT_ID from plf_jcr.TASK_PROJECTS where NAME NOT like '%bcdusers0098%' and NAME like '%-0%' and NAME like '%manager%') group by s.PROJECT_ID asc INTO OUTFILE '/tmp/1/00.txt';
  • SELECT s.PROJECT_ID,t.TASK_ID,t.TITLE, mod(t.TASK_ID,50) as aaa FROM plf_jcr.TASK_TASKS t inner join plf_jcr.TASK_STATUS s on t.STATUS_ID = s.STATUS_ID where s.PROJECT_ID in (406,407)  group by s.PROJECT_ID,aaa INTO OUTFILE '/tmp/labeledtask_10.txt';
  • select count(*) from product where STATUS IS NULL;
  • execute-a-mysql-command-from-a-shell-script >> mysql -h plfcap-mysql-server -uroot -ptest_control < update_db_connections.sql >> mysql -h plfcap-mysql-server -uroot -ptest_control database -e "SELECT * FROM blah WHERE foo='bar';" >> mysql -h plfcap-mysql-server -uroot -ptest_control -e >> mysql -h localhost -uroot -ptest_control -e "UPDATE TASK_TASKS SET END_DATE='2015-11-24 13:30:00', START_DATE='2015-11-24 13:00:00' WHERE END_DATE='2015-09-29 13:30:00' and START_DATE='2015-09-29 13:00:00'" plf_jcr
  • Some Where clause >> where NAME NOT like '%bcdusers0098%' and NAME like '%manager%'
  • Các câu lệnh khác:
    sudo service mysql stop ll /home/mysql/mysql/ pushd /home/mysql/mysql/ mv mysql ../mysql_db /home/mysql/mysql$ rm -rf * dirs sudo chmod 777 -R /home/mysql rm -f mysql mv ../mysql_db mysql sudo service mysql start sudo tail -100 /var/log/mysql/error.log mysql -uroot -p123456 use struts2_db; select * from catalog; /home/mysql/mysql$ popd cd /var/lib/mysql/backup-databases/EMPTY_DATASET

3. Import/Export MysqlDB
When backup mysql, it will dump some DB with options:
add-drop-database > data.sql
with these option, mysql will use only two(some) db names above, and it will delete the old db when importing.


Save query result to file:
mysql> SELECT order_id,product_name,qty FROM orders INTO OUTFILE '/tmp/orders.txt'
mysql> select TASK_ID,TITLE,CREATED_BY from TASK_TASKS where TASK_ID > 29 and MOD(TASK_ID,2520) < 50 INTO OUTFILE '/tmp/deletetasks.txt';


Import:
mysql -h127.0.0.1 -uroot -p123456 < data.sql;


Export query result to FILE:
mysql> select * from CATALOG INTO OUTFILE '/home/administrator/tmp/orders.txt';
Query OK, 8000 rows affected (0.00 sec)

4. Cài đặt mysql ở HĐH ubuntu/centos & others:
Ubuntu
  • sudo rm -rf /var/cache/apt/archives/*
  • sudo apt-get purge mysql* (sudo rm -rf /var/lib/mysql,sudo rm -rf /etc/mysql)
  • sudo apt-get autoremove
  • sudo apt-get autoclean (sudo apt-get dist-upgrade)
  • sudo dpkg --configure -a
  • sudo apt-get update
  • sudo apt-get install -f
  • sudo apt-get install mysql-client mysql-server
  • sudo apt-get install mysql-workbench
CentOS
  • yum install mysql-server
  • yum install mysql-bench
  • yum install mysql-devel
  • yum install php php-mysql php-common php-gd php-mbstring php-mcrypt php-devel php-xml
  • chkconfig httpd on OR /sbin/chkconfig httpd on
  • chkconfig mysqld on OR /sbin/chkconfig mysqld on OR /etc/init.d/mysqld start
  • chown -R mysql:mysql /var/lib/mysql/
  • service --status-all | grep mysqld =>'mysql dead but subsys locked'
  • cd /var/lock/subsys rm -f mysqld /etc/rc.d/init.d/mysqld restart
  • tar jxf phpMyAdmin-3.4.8-all-languages.tar.bz2
  • mv phpMyAdmin-3.4.8-all-languages phpmyadmin
  • cd phpmyadmin
  • cp config.sample.inc.php config.inc.php
  • gedit config.inc.php
  • $cfg['Servers'][$i]['auth_type'] = ‘http‘; # default is cookies
  • service httpd restart

POPULAR | PHỔ BIẾN

TAGS

VIEWS