This article describes the definition and uses of Task And Thread:

  • What is Task?
  • What is Thread?
  • Why do we need Task?
  • Why do we need Thread?
  • How to implement Task
  • How to implement Thread
    Differences between Task And Thread

What is Task?

  • .NET framework provides Threading.Tasks class to let you create tasks and run them asynchronously.
  • A task is an object that represents some work that should be done.
  • The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

    c#

What is Thread?

  • .NET Framework has thread-associated classes in System.Threading namespace.  
  • A Thread is a small set of executable instructions.
    c#

Why we need Task:

  1. It can be used whenever you want to execute something in parallel. Asynchronous implementation is easy in a task, using’ async’ and ‘await’ keywords.

Why we need Thread:

When the time comes when the application is required to perform few tasks at the same time.

How to create Task:

  1. static void Main(string[] args) {  
  2.     Task < string > obTask = Task.Run(() => (  
  3.         return“ Hello”));  
  4.     Console.WriteLine(obTask.result);  

How to create Thread:

  1. static void Main(string[] args) {  
  2.     Thread thread = new Thread(new ThreadStart(getMyName));  
  3.     thread.Start();  
  4. }  
  5. public void getMyName() {} 

Differences Between Task And Thread

  1. The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.
  2. The task can return a result. There is no direct mechanism to return the result from a thread.
  3. Task supports cancellation through the use of cancellation tokens. But Thread doesn't.
  4. A task can have multiple processes happening at the same time. Threads can only have one task running at a time.
  5. We can easily implement Asynchronous using ’async’ and ‘await’ keywords.
  6. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.
  7. A Task is a higher level concept than Thread.


'Knowledge' 카테고리의 다른 글

Cross Thread Operations in C#  (0) 2018.04.18
Aborting Thread Vs Cancelling Task  (0) 2018.04.18
Task And Thread In C#  (0) 2018.04.18
[.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15

방법: 텍스트 파일에서 읽기(C# 프로그래밍 가이드)

이 예제에서는 System.IO.File 클래스의 정적 메서드 ReadAllText 및 ReadAllLines를 사용하여 텍스트 파일의 내용을 읽습니다.

StreamReader를 사용하는 예제는 방법: 텍스트 파일을 한 번에 한 줄씩 읽기를 참조하세요.

참고

이 예제에 사용되는 파일은 방법: 텍스트 파일에 쓰기 항목에서 생성되었습니다.

예제

C#
class ReadFromFile
{
    static void Main()
    {
        // The files used in this example are created in the topic
        // How to: Write to a Text File. You can change the path and
        // file name to substitute text files of your own.

        // Example #1
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}


'Knowledge' 카테고리의 다른 글

Aborting Thread Vs Cancelling Task  (0) 2018.04.18
Task And Thread In C#  (0) 2018.04.18
[.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14



https://www.tutorialspoint.com/sqlite/index.htm




'Knowledge' 카테고리의 다른 글

Task And Thread In C#  (0) 2018.04.18
[.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27

1. Datatypes In SQLite

Most SQL database engines (every SQL database engine other than SQLite, as far as we know) uses static, rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.

SQLite uses a more general dynamic type system. In SQLite, the datatype of a value is associated with the value itself, not with its container. The dynamic type system of SQLite is backwards compatible with the more common static type systems of other database engines in the sense that SQL statements that work on statically typed databases should work the same way in SQLite. However, the dynamic typing in SQLite allows it to do things which are not possible in traditional rigidly typed databases.

2. Storage Classes and Datatypes

Each value stored in an SQLite database (or manipulated by the database engine) has one of the following storage classes:

  • NULL. The value is a NULL value.

  • INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).

  • BLOB. The value is a blob of data, stored exactly as it was input.

A storage class is more general than a datatype. The INTEGER storage class, for example, includes 6 different integer datatypes of different lengths. This makes a difference on disk. But as soon as INTEGER values are read off of disk and into memory for processing, they are converted to the most general datatype (8-byte signed integer). And so for the most part, "storage class" is indistinguishable from "datatype" and the two terms can be used interchangeably.

Any column in an SQLite version 3 database, except an INTEGER PRIMARY KEY column, may be used to store a value of any storage class.

All values in SQL statements, whether they are literals embedded in SQL statement text or parameters bound to precompiled SQL statements have an implicit storage class. Under circumstances described below, the database engine may convert values between numeric storage classes (INTEGER and REAL) and TEXT during query execution.

2.1. Boolean Datatype

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

2.2. Date and Time Datatype

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

3. Type Affinity

SQL database engines that use rigid typing will usually try to automatically convert values to the appropriate datatype. Consider this:

CREATE TABLE t1(a INT, b VARCHAR(10));
INSERT INTO t1(a,b) VALUES('123',456);

Rigidly-typed database will convert the string '123' into an integer 123 and the integer 456 into a string '456' prior to doing the insert.

In order to maximize compatibility between SQLite and other database engines, and so that the example above will work on SQLite as it does on other SQL database engines, SQLite supports the concept of "type affinity" on columns. The type affinity of a column is the recommended type for data stored in that column. The important idea here is that the type is recommended, not required. Any column can still store any type of data. It is just that some columns, given the choice, will prefer to use one storage class over another. The preferred storage class for a column is called its "affinity".

Each column in an SQLite 3 database is assigned one of the following type affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

(Historical note: The "BLOB" type affinity used to be called "NONE". But that term was easy to confuse with "no affinity" and so it was renamed.)

A column with TEXT affinity stores all data using storage classes NULL, TEXT or BLOB. If numerical data is inserted into a column with TEXT affinity it is converted into text form before being stored.

A column with NUMERIC affinity may contain values using all five storage classes. When text data is inserted into a NUMERIC column, the storage class of the text is converted to INTEGER or REAL (in order of preference) if such conversion is lossless and reversible. For conversions between TEXT and REAL storage classes, SQLite considers the conversion to be lossless and reversible if the first 15 significant decimal digits of the number are preserved. If the lossless conversion of TEXT to INTEGER or REAL is not possible then the value is stored using the TEXT storage class. No attempt is made to convert NULL or BLOB values.

A string might look like a floating-point literal with a decimal point and/or exponent notation but as long as the value can be expressed as an integer, the NUMERIC affinity will convert it into an integer. Hence, the string '3.0e+5' is stored in a column with NUMERIC affinity as the integer 300000, not as the floating point value 300000.0.

A column that uses INTEGER affinity behaves the same as a column with NUMERIC affinity. The difference between INTEGER and NUMERIC affinity is only evident in a CAST expression.

A column with REAL affinity behaves like a column with NUMERIC affinity except that it forces integer values into floating point representation. (As an internal optimization, small floating point values with no fractional component and stored in columns with REAL affinity are written to disk as integers in order to take up less space and are automatically converted back into floating point as the value is read out. This optimization is completely invisible at the SQL level and can only be detected by examining the raw bits of the database file.)

A column with affinity BLOB does not prefer one storage class over another and no attempt is made to coerce data from one storage class into another.

3.1. Determination Of Column Affinity

The affinity of a column is determined by the declared type of the column, according to the following rules in the order shown:

  1. If the declared type contains the string "INT" then it is assigned INTEGER affinity.

  2. If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice that the type VARCHAR contains the string "CHAR" and is thus assigned TEXT affinity.

  3. If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity BLOB.

  4. If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.

  5. Otherwise, the affinity is NUMERIC.

Note that the order of the rules for determining column affinity is important. A column whose declared type is "CHARINT" will match both rules 1 and 2 but the first rule takes precedence and so the column affinity will be INTEGER.

3.1.1. Affinity Name Examples

The following table shows how many common datatype names from more traditional SQL implementations are converted into affinities by the five rules of the previous section. This table shows only a small subset of the datatype names that SQLite will accept. Note that numeric arguments in parentheses that following the type name (ex: "VARCHAR(255)") are ignored by SQLite - SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values.

Example Typenames From The
CREATE TABLE Statement
or CAST Expression
Resulting AffinityRule Used To Determine Affinity
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
INTEGER1
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
TEXT2
BLOB
no datatype specified
BLOB3
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
REAL4
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME
NUMERIC5

Note that a declared type of "FLOATING POINT" would give INTEGER affinity, not REAL affinity, due to the "INT" at the end of "POINT". And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.

3.2. Affinity Of Expressions

Every table column has a type affinity (one of BLOB, TEXT, INTEGER, REAL, or NUMERIC) but expressions do no necessarily have an affinity.

Expression affinity is determined by the following rules:

  • The right-hand operand of an IN or NOT IN operator has no affinity if the operand is a list and has the same affinity as the affinity of the result set expression if the operand is a SELECT.

  • When an expression is a simple reference to a column of a real table (not a VIEW or subquery) then the expression has the same affinity as the table column.

    • Parentheses around the column name are ignored. Hence if X and Y.Z are column names, then (X) and (Y.Z) are also considered column names and have the affinity of the corresponding columns.

    • Any operators applied to column names, including the no-op unary "+" operator, convert the column name into an expression which always has no affinity. Hence even if X and Y.Z are column names, the expressions +X and +Y.Z are not column names and have no affinity.

  • An expression of the form "CAST(expr AS type)" has an affinity that is the same as a column with a declared type of "type".

  • Otherwise, an expression has no affinity.

3.3. Column Affinity For Views And Subqueries

The "columns" of a VIEW or FROM-clause subquery are really the expressions in the result set of the SELECT statement that implements the VIEW or subquery. Thus, the affinity for columns of a VIEW or subquery are determined by the expression affinity rules above. Consider an example:

CREATE TABLE t1(a INT, b TEXT, c REAL);
CREATE VIEW v1(x,y,z) AS SELECT b, a+c, 42 FROM t1 WHERE b!=11;

The affinity of the v1.x column will be the same as the affinity of t1.b (INTEGER), since v1.x maps directly into t1.b. But columns v1.y and v1.z both have no affinity, since those columns map into expression a+c and 42, and expressions always have no affinity.

When the SELECT statement that implements a VIEW or FROM-clause subquery is a compound SELECT then the affinity of each supposed column of the VIEW or subquery will be the affinity of the corresponding result column for one of the individual SELECT statements that make up the compound. However, it is indeterminate which of the SELECT statements will be used to determine affinity. Different constituent SELECT statements might be used to determine affinity at different times during query evaluation. Best practice is to avoid mixing affinities in a compound SELECT.

3.4. Column Affinity Behavior Example

The following SQL demonstrates how SQLite uses column affinity to do type conversions when values are inserted into a table.

CREATE TABLE t1(
    t  TEXT,     -- text affinity by rule 2
    nu NUMERIC,  -- numeric affinity by rule 5
    i  INTEGER,  -- integer affinity by rule 1
    r  REAL,     -- real affinity by rule 4
    no BLOB      -- no affinity by rule 3
);

-- Values stored as TEXT, INTEGER, INTEGER, REAL, TEXT.
INSERT INTO t1 VALUES('500.0', '500.0', '500.0', '500.0', '500.0');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|text

-- Values stored as TEXT, INTEGER, INTEGER, REAL, REAL.
DELETE FROM t1;
INSERT INTO t1 VALUES(500.0, 500.0, 500.0, 500.0, 500.0);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|real

-- Values stored as TEXT, INTEGER, INTEGER, REAL, INTEGER.
DELETE FROM t1;
INSERT INTO t1 VALUES(500, 500, 500, 500, 500);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|integer

-- BLOBs are always stored as BLOBs regardless of column affinity.
DELETE FROM t1;
INSERT INTO t1 VALUES(x'0500', x'0500', x'0500', x'0500', x'0500');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
blob|blob|blob|blob|blob

-- NULLs are also unaffected by affinity
DELETE FROM t1;
INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
null|null|null|null|null

4. Comparison Expressions

SQLite version 3 has the usual set of SQL comparison operators including "=", "==", "<", "<=", ">", ">=", "!=", "", "IN", "NOT IN", "BETWEEN", "IS", and "IS NOT", .

4.1. Sort Order

The results of a comparison depend on the storage classes of the operands, according to the following rules:

  • A value with storage class NULL is considered less than any other value (including another value with storage class NULL).

  • An INTEGER or REAL value is less than any TEXT or BLOB value. When an INTEGER or REAL is compared to another INTEGER or REAL, a numerical comparison is performed.

  • A TEXT value is less than a BLOB value. When two TEXT values are compared an appropriate collating sequence is used to determine the result.

  • When two BLOB values are compared, the result is determined using memcmp().

4.2. Type Conversions Prior To Comparison

SQLite may attempt to convert values between the storage classes INTEGER, REAL, and/or TEXT before performing a comparison. Whether or not any conversions are attempted before the comparison takes place depends on the type affinity of the operands.

To "apply affinity" means to convert an operand to a particular storage class if and only if the conversion is lossless and reversible. Affinity is applied to operands of a comparison operator prior to the comparison according to the following rules in the order shown:

  • If one operand has INTEGER, REAL or NUMERIC affinity and the other operand has TEXT or BLOB or no affinity then NUMERIC affinity is applied to other operand.

  • If one operand has TEXT affinity and the other has no affinity, then TEXT affinity is applied to the other operand.

  • Otherwise, no affinity is applied and both operands are compared as is.

The expression "a BETWEEN b AND c" is treated as two separate binary comparisons "a >= b AND a <= c", even if that means different affinities are applied to 'a' in each of the comparisons. Datatype conversions in comparisons of the form "x IN (SELECT y ...)" are handled is if the comparison were really "x=y". The expression "a IN (x, y, z, ...)" is equivalent to "a = +x OR a = +y OR a = +z OR ...". In other words, the values to the right of the IN operator (the "x", "y", and "z" values in this example) are considered to have no affinity, even if they happen to be column values or CAST expressions.

4.3. Comparison Example

CREATE TABLE t1(
    a TEXT,      -- text affinity
    b NUMERIC,   -- numeric affinity
    c BLOB,      -- no affinity
    d            -- no affinity
);

-- Values will be stored as TEXT, INTEGER, TEXT, and INTEGER respectively
INSERT INTO t1 VALUES('500', '500', '500', 500);
SELECT typeof(a), typeof(b), typeof(c), typeof(d) FROM t1;
text|integer|text|integer

-- Because column "a" has text affinity, numeric values on the
-- right-hand side of the comparisons are converted to text before
-- the comparison occurs.
SELECT a < 40,   a < 60,   a < 600 FROM t1;
0|1|1

-- Text affinity is applied to the right-hand operands but since
-- they are already TEXT this is a no-op; no conversions occur.
SELECT a < '40', a < '60', a < '600' FROM t1;
0|1|1

-- Column "b" has numeric affinity and so numeric affinity is applied
-- to the operands on the right.  Since the operands are already numeric,
-- the application of affinity is a no-op; no conversions occur.  All
-- values are compared numerically.
SELECT b < 40,   b < 60,   b < 600 FROM t1;
0|0|1

-- Numeric affinity is applied to operands on the right, converting them
-- from text to integers.  Then a numeric comparison occurs.
SELECT b < '40', b < '60', b < '600' FROM t1;
0|0|1

-- No affinity conversions occur.  Right-hand side values all have
-- storage class INTEGER which are always less than the TEXT values
-- on the left.
SELECT c < 40,   c < 60,   c < 600 FROM t1;
0|0|0

-- No affinity conversions occur.  Values are compared as TEXT.
SELECT c < '40', c < '60', c < '600' FROM t1;
0|1|1

-- No affinity conversions occur.  Right-hand side values all have
-- storage class INTEGER which compare numerically with the INTEGER
-- values on the left.
SELECT d < 40,   d < 60,   d < 600 FROM t1;
0|0|1

-- No affinity conversions occur.  INTEGER values on the left are
-- always less than TEXT values on the right.
SELECT d < '40', d < '60', d < '600' FROM t1;
1|1|1

All of the result in the example are the same if the comparisons are commuted - if expressions of the form "a<40" are rewritten as "40>a".

5. Operators

All mathematical operators (+, -, *, /, %, <<, >>, &, and |) cast both operands to the NUMERIC storage class prior to being carried out. The cast is carried through even if it is lossy and irreversible. A NULL operand on a mathematical operator yields a NULL result. An operand on a mathematical operator that does not look in any way numeric and is not NULL is converted to 0 or 0.0.

6. Sorting, Grouping and Compound SELECTs

When query results are sorted by an ORDER BY clause, values with storage class NULL come first, followed by INTEGER and REAL values interspersed in numeric order, followed by TEXT values in collating sequence order, and finally BLOB values in memcmp() order. No storage class conversions occur before the sort.

When grouping values with the GROUP BY clause values with different storage classes are considered distinct, except for INTEGER and REAL values which are considered equal if they are numerically equal. No affinities are applied to any values as the result of a GROUP by clause.

The compound SELECT operators UNION, INTERSECT and EXCEPT perform implicit comparisons between values. No affinity is applied to comparison operands for the implicit comparisons associated with UNION, INTERSECT, or EXCEPT - the values are compared as is.

7. Collating Sequences

When SQLite compares two strings, it uses a collating sequence or collating function (two words for the same thing) to determine which string is greater or if the two strings are equal. SQLite has three built-in collating functions: BINARY, NOCASE, and RTRIM.

  • BINARY - Compares string data using memcmp(), regardless of text encoding.
  • NOCASE - The same as binary, except the 26 upper case characters of ASCII are folded to their lower case equivalents before the comparison is performed. Note that only ASCII characters are case folded. SQLite does not attempt to do full UTF case folding due to the size of the tables required.
  • RTRIM - The same as binary, except that trailing space characters are ignored.

An application can register additional collating functions using the sqlite3_create_collation() interface.

7.1. Assigning Collating Sequences from SQL

Every column of every table has an associated collating function. If no collating function is explicitly defined, then the collating function defaults to BINARY. The COLLATE clause of the column definition is used to define alternative collating functions for a column.

The rules for determining which collating function to use for a binary comparison operator (=, <, >, <=, >=, !=, IS, and IS NOT) are as follows:

  1. If either operand has an explicit collating function assignment using the postfix COLLATE operator, then the explicit collating function is used for comparison, with precedence to the collating function of the left operand.

  2. If either operand is a column, then the collating function of that column is used with precedence to the left operand. For the purposes of the previous sentence, a column name preceded by one or more unary "+" operators is still considered a column name.

  3. Otherwise, the BINARY collating function is used for comparison.

An operand of a comparison is considered to have an explicit collating function assignment (rule 1 above) if any subexpression of the operand uses the postfix COLLATE operator. Thus, if a COLLATE operator is used anywhere in a comparision expression, the collating function defined by that operator is used for string comparison regardless of what table columns might be a part of that expression. If two or more COLLATE operatorsubexpressions appear anywhere in a comparison, the left most explicit collating function is used regardless of how deeply the COLLATE operators are nested in the expression and regardless of how the expression is parenthesized.

The expression "x BETWEEN y and z" is logically equivalent to two comparisons "x >= y AND x <= z" and works with respect to collating functions as if it were two separate comparisons. The expression "x IN (SELECT y ...)" is handled in the same way as the expression "x = y" for the purposes of determining the collating sequence. The collating sequence used for expressions of the form "x IN (y, z, ...)" is the collating sequence of x.

Terms of the ORDER BY clause that is part of a SELECT statement may be assigned a collating sequence using the COLLATE operator, in which case the specified collating function is used for sorting. Otherwise, if the expression sorted by an ORDER BY clause is a column, then the collating sequence of the column is used to determine sort order. If the expression is not a column and has no COLLATE clause, then the BINARY collating sequence is used.

7.2. Collation Sequence Examples

The examples below identify the collating sequences that would be used to determine the results of text comparisons that may be performed by various SQL statements. Note that a text comparison may not be required, and no collating sequence used, in the case of numeric, blob or NULL values.

CREATE TABLE t1(
    x INTEGER PRIMARY KEY,
    a,                 /* collating sequence BINARY */
    b COLLATE BINARY,  /* collating sequence BINARY */
    c COLLATE RTRIM,   /* collating sequence RTRIM  */
    d COLLATE NOCASE   /* collating sequence NOCASE */
);
                   /* x   a     b     c       d */
INSERT INTO t1 VALUES(1,'abc','abc', 'abc  ','abc');
INSERT INTO t1 VALUES(2,'abc','abc', 'abc',  'ABC');
INSERT INTO t1 VALUES(3,'abc','abc', 'abc ', 'Abc');
INSERT INTO t1 VALUES(4,'abc','abc ','ABC',  'abc');
 
/* Text comparison a=b is performed using the BINARY collating sequence. */
SELECT x FROM t1 WHERE a = b ORDER BY x;
--result 1 2 3

/* Text comparison a=b is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE a = b COLLATE RTRIM ORDER BY x;
--result 1 2 3 4

/* Text comparison d=a is performed using the NOCASE collating sequence. */
SELECT x FROM t1 WHERE d = a ORDER BY x;
--result 1 2 3 4

/* Text comparison a=d is performed using the BINARY collating sequence. */
SELECT x FROM t1 WHERE a = d ORDER BY x;
--result 1 4

/* Text comparison 'abc'=c is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE 'abc' = c ORDER BY x;
--result 1 2 3

/* Text comparison c='abc' is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE c = 'abc' ORDER BY x;
--result 1 2 3

/* Grouping is performed using the NOCASE collating sequence (Values
** 'abc', 'ABC', and 'Abc' are placed in the same group). */
SELECT count(*) FROM t1 GROUP BY d ORDER BY 1;
--result 4

/* Grouping is performed using the BINARY collating sequence.  'abc' and
** 'ABC' and 'Abc' form different groups */
SELECT count(*) FROM t1 GROUP BY (d || '') ORDER BY 1;
--result 1 1 2

/* Sorting or column c is performed using the RTRIM collating sequence. */
SELECT x FROM t1 ORDER BY c, x;
--result 4 1 2 3

/* Sorting of (c||'') is performed using the BINARY collating sequence. */
SELECT x FROM t1 ORDER BY (c||''), x;
--result 4 2 3 1

/* Sorting of column c is performed using the NOCASE collating sequence. */
SELECT x FROM t1 ORDER BY c COLLATE NOCASE, x;
--result 2 4 3 1


'Knowledge' 카테고리의 다른 글

[.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23

메소드 콜에서 UI를 조작하면 다중 스레드에서 에러 발생합니다. 주의해주세요. 

Control.Invoke 에서 행업 걸립니다...

BeginInvoke에서는 괜찮지만, EndInvoke 에서 행업걸립니다...

다중 스레드에서 컨트롤러 표기에 관한 부분은 메소드 콜에서 자제해주세요.



MainPage 클레스에 정적 LogMethod 메소드를 만들어 주세요. 

Rule에 의해 움직이기 때문에, 해당 클레스 뿐 아니라 다른 곳에서 찎은 로그도 이곳에 로그가 발생합니다.


// NLog 이벤트 등록 메소드

private void Register_NLog_MethodCall()

{

MethodCallTarget target = new MethodCallTarget();

target.ClassName = typeof(MainPage).AssemblyQualifiedName;

target.MethodName = "LogMethod";

target.Parameters.Add(new MethodCallParameter("${level}"));

target.Parameters.Add(new MethodCallParameter("${message}"));


var wrapper = new AsyncTargetWrapper(target, 5000, AsyncTargetWrapperOverflowAction.Discard);

var rule = new LoggingRule("*", LogLevel.Trace, target);


NLog.LogManager.Configuration.AddTarget("method", wrapper);

NLog.LogManager.Configuration.LoggingRules.Add(rule);

NLog.LogManager.ReconfigExistingLoggers();


// 리스트 박스 등록

_lbx = lbx_log;

}

'Knowledge > NLog' 카테고리의 다른 글

NLog 설정 Programmically 등록 (수동)  (0) 2018.04.26
[.NET] NLog Event Register 콜백 이벤트  (0) 2018.04.14




Use a SQLite database in a UWP app - UWP app developer _ Microso


SDK 버전 맞추는 거 유의하세요.



'Knowledge' 카테고리의 다른 글

[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16

' 전역변수 선언은 이렇게 밖에다 할 수 있다.

' Global keyword는 vb6에서는 사용되지 않는다.


Public LogName As String


Private Sub AddItem_Init(key As String, value As String)

    

    Dim category As String

    Dim message As String

    

    LogName = "practice.ini"

    category = "General"

    message = "[key]:{key}   [value]:{value}"

    

    message = Replace(message, "{key}", key)

    message = Replace(message, "{value}", value)

    

    

    Call fn_WritePrivateProfileString(LogName, category, key, value)

    Call sb_SaveLog(App.EXEName, message)

    

End Sub

'Knowledge > Visual Basic 6+' 카테고리의 다른 글

[VB6] 상수 선언  (0) 2018.05.09
VB6 단축키  (0) 2018.04.19
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26

Replace Function - Visual Basic 6.0 (VB 6.0)

Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Syntax:
Replace(expression, find, replace[, start[, count[, compare]]])
ParameterDescription
expressionRequired. String expression containing substring to replace.
findRequired. Substring being searched for.
replaceRequired. Replacement substring.
startOptional. Default 1. Position within expression where substring search is to begin.
countOptional. Default -1 (All). Number of substring substitutions to perform.
compareOptional. Default vbBinaryCompare (0). Numeric value indicating the kind of comparison to use when evaluating substrings.

Return Data type:
String
Example:

Dim St as String
St = "Chennaiiq"


StatementResultRemark
Replace(St, "n", "m")Chemmaiiq 
Replace(St, "N", "m")Chennaiiq 
Replace(St, "n", "M")CheMMaiiq 
Replace(St, "n", "m", 5)maiiq 
Replace(St, "n", "m", 4, 1)mnaiiq 
Replace("", "n", "m") Empty String
Replace(null, "n", "m")ErrorInvalid use of null
Replace(St, "", "m")Chennaiiq(Copy of Expression)
Replace(St, "n", "")Cheaiiq 
Replace(St, "n", "m", 20) Empty String
Replace(St, "n", "m", 1, 0)Chennaiiq 


'Knowledge > Visual Basic 6+' 카테고리의 다른 글

VB6 단축키  (0) 2018.04.19
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26
For...Next Statement (Visual Basic)  (0) 2018.03.13

변수

변수란 값을 담아두는 것이라고 모두 알고 있으실 겁니다.

우선 간단하게 변수를 생성하고 설정하는 방법을 알아보겠습니다.

--변수 생성
--declare 변수명 타입
DECLARE @name varchar(20)

--변수에 값 할당
SET @name = 'Kendrick'

--혹은
--userid가 sonim1일 때 이름이 Kendrick일 경우  
SELECT @name = P.name FROM tblPerson P WHERE userid = 'sonim1'

SET을 하던 SELECT를 하던 동일한 값이 @name 변수에 할당되는 쿼리입니다.

아래는 @name 변수를 이용해서 이어서 해당 user의 가입일을 알아보겠습니다.

SELECT CreateDate -- 생성일 필드
FROM  tblPerson P
WHERE P.name = @name

이정도면 변수의 사용법은 충분히 이해되실것 입니다.

테이블 변수

이제 알아볼 항목은 테이블 변수입니다.
변수에서는 값뿐이 아니라 여러행으로 떨어지는 결과를 담아 둘 수 있습니다.

예를 보 시죠

--테이블 변수 생성, 자료형 대신에 테이블 스키마가 들어가 있다.
DECLARE @userData TABLE(
     name varchar(30) NOT NULL,
     CreateDate datetime NOT NULL
);

--Insert Into Select 문을 이용하여 k로 시작하는 회원의 리스트를 할당해보자
INSERT INTO @userData
SELECT name, CreateDate 
FROM tblPerson
WHERE name like 'k%'

--할당 후에는 변수를 이용하여 테이블처럼 사용가능하다.
SELECT * FROM @userData

변수와 테이블 변수에 대해서 간단하게 알아보았습니다.
테이블 변수를 이용하여 쿼리의 복잡성을 떨어트릴수 있으며, 속도 개선에 많은 도움이 될 것입니다.

테이블 변수와 임시 테이블의 차이점

임시테이블테이블 변수
존재 기간명시적으로 삭제를 안할 시에는 세션 연결 기간동안 존재명시적으로 삭제를 안할 시에는 배치 처리기간 동안 존재
저장소TempdbTempdb
쿼리비용대용량에서는 쿼리 비용 유리소용량에서 쿼리 비용 유리
장단점대용량 데이터 처리에 유리소용량 데이터 처리에서 유리
세션 단위 처리시에 사용저장 프로시져에서 테이블 변수 사용하면 임시 테이블 사용할 떄보다 저장 프로시저를 다시 컴파일하는 일이 줄어듦
배치 처리 단위인 저장 프로시져에서 사용 유리

마치며

잘못 사용하면 성능상 문제가 있겠지만 잘 사용하면 너무나 유용한 기능입니다. 물론 말은 쉽습니다. 하하
사실 잘못 사용하기가 더 어려운 기능이겠네요. !!
좋은 하루 되세요

테이블 변수 임시 테이블 차이점 표 출처 : RunHanii 블로그

'Knowledge' 카테고리의 다른 글

[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (0) 2018.03.16

VB6 문법 모음 페이지


# Call Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/call-statement


# Error Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/error-statement


# DO...Loop Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/do-loop-statement


# Exit Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement

vb6 What is Me.Caption


Hi, starting out in vb and working through some exercises and am confronted with a line of code

OldCaption = Me.Caption

The question is what is Me."xxxxxxxxx" and what applications can it be used for.


Many thanks in advance...Andy


--------------------------------------------------------------------------------------------------------------------------------


What is Me?

Me is the form itself. It is just a shorthand of using the form name. So Me.Caption and Formname.Caption is the same.



  OldCaption = Me.Caption

Above code simply saves the caption of the form to a variable named OldCaption.


hongjun


[MSSQL] 사용자 추가.pdf


'Knowledge' 카테고리의 다른 글

[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (0) 2018.03.16
Encoding URL  (0) 2018.03.07

MS-SQL 테이블 복사


1. 테이블을 생성하면서 테이블의 데이타 복사


select * into 생성될테이블명 from 원본테이블명


테이블 구조만 복사하겠다면

select * into 생성될테이블명 from 원본테이블명 where 1=2


2. 테이블이 이미 생성되어 있는경우 데이타만 복사


insert into 카피될테이블명 select * from 원본테이블명


특정 데이타만 복사 하겠다면

insert into 카피될테이블명 select * from 원본테이블명 where 검색조건




출처: http://iberis.tistory.com/10 [Iberis]

'Knowledge' 카테고리의 다른 글

[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (0) 2018.03.16
Encoding URL  (0) 2018.03.07
PSTN  (0) 2018.03.04

날짜 및 시간 데이터 형식 및 함수(Transact-SQL)

이 항목은 다음에 적용됩니다.예SQL Server(2012부터)아니요Azure SQL Database아니요Azure SQL Data Warehouse 아니요병렬 데이터 웨어하우스

이 항목의 다음 섹션에서는 Transact-SQL의 모든 날짜/시간 데이터 형식 및 함수에 대한 개요를 제공합니다.

날짜 및 시간 데이터 형식

Transact-SQL 날짜 및 시간 데이터 형식이 다음 표에 나열 되어 있습니다.

데이터 형식형식범위정확도저장소 크기(바이트)사용자 정의 초 소수 부분 자릿수표준 시간대 오프셋
timehh:mm:ss[.nnnnnnn]00:00:00.0000000부터 23:59:59.9999999까지100나노초3 ~ 5아니요
dateYYYY-MM-DD0001-01-01부터 31.12.99까지1일3아니요아니요
smalldatetimeYYYY-MM-DD hh:mm:ss1900-01-01부터 2079-06-06까지1분4아니요아니요
datetimeYYYY-MM-DD hh:mm:ss[.nnn]1753-01-01부터 9999-12-31까지0.00333초8아니요아니요
datetime2YYYY-MM-DD hh:mm:ss[.nnnnnnn]0001-01-01 00:00:00.0000000부터 9999-12-31 23:59:59.9999999까지100나노초6 ~ 8아니요
datetimeoffsetYYYY-월-일 h:mm: ss [.nnnnnnn] [+ |-] hh: mm0001-01-01 00:00:00.0000000부터 9999-12-31 23:59:59.9999999까지(UTC)100나노초8 ~ 10

Note

Transact-SQL rowversion 데이터 형식이 날짜 또는 시간 데이터 형식 않습니다. 타임 스탬프 에 대 한 사용 되지 않는 동의어 rowversion합니다.

날짜 및 시간 함수

다음 표에는 Transact-SQL 날짜 및 시간 함수가 나와 있습니다. 결정성에 대 한 자세한 내용은 참조Deterministic and Nondeterministic Functions합니다.

시스템 날짜 및 시간 값 가져오기 함수

모든 시스템 날짜 및 시간 값은 SQL Server 인스턴스가 실행 중인 컴퓨터 운영 체제에서 가져옵니다.

정밀도가 높은 시스템 날짜 및 시간 함수

SQL Server 2017GetSystemTimeAsFileTime() Windows API를 사용 하 여 날짜 및 시간 값을 가져옵니다. 정확도는 SQL Server 인스턴스가 실행되고 있는 컴퓨터의 하드웨어와 Windows 버전에 따라 달라집니다. 이 API의 정밀도는 100나노초로 고정됩니다. GetSystemTimeAdjustment() Windows API를 사용 하 여 정확도 확인할 수 있습니다.

'Knowledge' 카테고리의 다른 글

[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (0) 2018.03.16
Encoding URL  (0) 2018.03.07
PSTN  (0) 2018.03.04
C# Winforms Message Box  (0) 2018.03.04

For...Next Statement (Visual Basic)

Repeats a group of statements a specified number of times.

Syntax

For counter [ As datatype ] = start To end [ Step step ]  
    [ statements ]  
    [ Continue For ]  
    [ statements ]  
    [ Exit For ]  
    [ statements ]  
Next [ counter ]  

Parts

PartDescription
counterRequired in the For statement. Numeric variable. The control variable for the loop. For more information, see Counter Argument later in this topic.
datatypeOptional. Data type of counter. For more information, see Counter Argument later in this topic.
startRequired. Numeric expression. The initial value of counter.
endRequired. Numeric expression. The final value of counter.
stepOptional. Numeric expression. The amount by which counter is incremented each time through the loop.
statementsOptional. One or more statements between For and Next that run the specified number of times.
Continue ForOptional. Transfers control to the next loop iteration.
Exit ForOptional. Transfers control out of the For loop.
NextRequired. Terminates the definition of the For loop.

Note

The To keyword is used in this statement to specify the range for the counter. You can also use this keyword in the Select...Case Statement and in array declarations. For more information about array declarations, see Dim Statement.

Simple Examples

You use a For...Next structure when you want to repeat a set of statements a set number of times.

In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

VB
For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

In the following example, the number variable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value of number reaches 0. The Step argument of -.25 reduces the value by 0.25 on each iteration of the loop.

VB
For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0 

Tip

A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times to run the statements in the loop. However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.

Nesting Loops

You can nest For loops by putting one loop within another. The following example demonstrates nested For...Next structures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.

VB
For indexA = 1 To 3
    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Append to the StringBuilder every third number
    ' from 20 to 1 descending.
    For indexB = 20 To 1 Step -3
        sb.Append(indexB.ToString)
        sb.Append(" ")
    Next indexB

    ' Display the line.
    Debug.WriteLine(sb.ToString)
Next indexA
' Output:
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2

When nesting loops, each loop must have a unique counter variable.

You can also nest different kinds control structures within each other. For more information, see Nested Control Structures.

Exit For and Continue For

The Exit For statement immediately exits the ForNext loop and transfers control to the statement that follows the Next statement.

The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement.

The following example illustrates the use of the Continue For and Exit For statements.

VB
For index As Integer = 1 To 100000
    ' If index is between 5 and 7, continue
    ' with the next iteration.
    If index >= 5 And index <= 8 Then
        Continue For
    End If

    ' Display the index.
    Debug.Write(index.ToString & " ")

    ' If index is 10, exit the loop.
    If index = 10 Then
        Exit For
    End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10

You can put any number of Exit For statements in a ForNext loop. When used within nested ForNextloops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.

Exit For is often used after you evaluate some condition (for example, in an If...Then...Else structure). You might want to use Exit For for the following conditions:

  • Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.

  • A Try...Catch...Finally statement catches an exception. You might use Exit For at the end of the Finally block.

  • You have an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement.

Technical Implementation

When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs.

Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the Forstatement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered.

The loop doesn't stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative.

If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.

If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Step Argument

The value of step can be either positive or negative. This parameter determines loop processing according to the following table:

Step valueLoop executes if
Positive or zerocounter <= end
Negativecounter >= end

The default value of step is 1.

Counter Argument

The following table indicates whether counter defines a new local variable that’s scoped to the entire For…Nextloop. This determination depends on whether datatype is present and whether counter is already defined.

Is datatypepresent?Is counteralready defined?Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
NoYesNo, because counter is already defined. If the scope of counter isn't local to the procedure, a compile-time warning occurs.
NoNoYes. The data type is inferred from the start, end, and step expressions. For information about type inference, see Option Infer Statement and Local Type Inference.
YesYesYes, but only if the existing counter variable is defined outside the procedure. That variable remains separate. If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.
YesNoYes.

The data type of counter determines the type of the iteration, which must be one of the following types:

  • A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • An enumeration that you declare by using an Enum Statement.

  • An Object.

  • A type T that has the following operators, where B is a type that can be used in a Booleanexpression.

    Public Shared Operator >= (op1 As T, op2 As T) As B

    Public Shared Operator <= (op1 As T, op2 As T) As B

    Public Shared Operator - (op1 As T, op2 As T) As T

    Public Shared Operator + (op1 As T, op2 As T) As T

You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement.

The start, end, and step expressions can evaluate to any data type that widens to the type of counter. If you use a user-defined type for counter, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.

+ Recent posts