Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Tuesday, 10 July 2012

Database in recovery



If this is 2005, this might be what you need:

 
select der.session_id, der.command, der.status, der.percent_complete, *
from sys.dm_exec_requests as der


It works for other types of commands that have known progress indicators.  If not, then I really don't think it tells you.  You might also check the error log to see how long it took the previous time...

Monday, 9 July 2012

Create and Use a Sample SQL Cursor and T-SQL Cursor Example Code

Here is a SQL cursor example code created for looping through a list of records as a result of a select query, which enables the sql developer to execute a stored procedure for each row in the cursor which use the values fetched by the cursor as the input arguments. The sample cursor is developed on a MS SQL Server and is a sample for sql server cursor. The sql codes may use t-sql codes so the sql cursor example may have differences than a typical pl/sql cursor or an Oracle cursor.

The sample sql cursor codes below illustrates a process of merging duplicate customer records kept in an application database. Assume that the duplicate customers list and relation among the duplicate customer records are inserted into and kept in a table named DuplicateCustomers which is simply formed of columns MasterCustomerId, DuplicateCustomerId and some other columns like MergeDate, IsMerged, MergedByUserId, InsertedDate, InsertedByUserId, etc which are used during processing some details and useful in the reporting of the duplicate record merge process results.


The list of the original customer records and the duplicate customer records can be selected by the sql select query below:
SELECT MasterCustomerId, DuplicateCustomerId
FROM DuplicateCustomers WHERE IsMerged = 0

You can either create a temporary table to keep the result set in order to use your initial set of records in the next steps of your process. Or you can just use the above transact sql query to supply your records set to feed the t-sql cursor example we will create.

Here with the variable declarations we will set column values we fetch with the tsql cursor to the variables.
DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DuplicateId Int

Then the sql cursor definition or the t-sql cursor declaration code takes place.
DECLARE merge_cursor CURSOR FAST_FORWARD FOR
SELECT MasterCustomerId, DuplicateCustomerId
FROM DuplicateCustomers WHERE IsMerged = 0

During the example sql cursor declaration you can set the sql cursor properties or the attributes of the cursor. Note that the sample cursor declaration uses the FAST_FORWARD key attribute in order to create a sql cursor with a high performance. Since FAST_FORWARD states that the cursor is FORWARD_ONLY and READ_ONLY the performance of the cursor is optimized.

The t-sql syntax of cursor declaration command DECLARE CURSOR is stated as below in MSDN :
DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]

You can find more on how to declare a t-sql cursor and cursor attributes in Books Online

With the call of the OPEN command the t-sql server cursor is opened and the cursor is populated with the data by the execution of the select query of the DECLARE CURSOR command.
OPEN merge_cursor

So the OPEN command runs or executes the "SELECT MasterCustomerId, DuplicateCustomerId FROM DuplicateCustomers WHERE IsMerged = 0" select query defined in the DECLARE CURSOR definition command which is set after FOR key. With the execution of this select query the cursor is populated with the rows or the data returned as a result set of the query.

The next step in using a cursor is fetching the rows from the populated cursor one by one.
FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId

The syntax of the FETCH command is as follows
FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
]
{ { [ GLOBAL ] cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ]

With the use of the NEXT, the FETCH NEXT command returns the next row following the current row. If FETCH NEXT is called for the first time for a cursor, or we can say if it is called after the OPEN CURSOR command, then the first row in the returned result set is fetched or returned. The column values in the returned row can be set into variables with the INTO key and by giving the names of the variables as a comma seperated list after the INTO key.

So for our example the first row in the return result set of the cursor is set into two variables named @MasterId and @DuplicateId. Here one important point is the first column of the result set (column named MasterCustomerId) is set to first variable defined in the list which is the @MasterId variable. And the secod column named DuplicateCustomerId is set to the second variable @DuplicateId.

So the variable types must be carefully declared according to the column types of the selected rows.

After the FETCH command, you should always control the value of the @@FETCH_STATUS. This variable returns the status of the last cursor FETCH command in the current connection.

The possible return values of @@FETCH_STATUS are;















0FETCH statement was successful
-1FETCH statement failed or the row was beyond the result set
-2Row fetched is missing

By always checking the @@FETCH_STATUS and controlling that it is value is equal to "0" we will have a new row fetched. When the fetched status is different than the "0" we can say that we have no more records are fetched. In short, the value of @@FETCH_STATUS variable is the controlling parameter of the loop we will use during processing all records or rows in the cursor.

In the body part of the WHILE statement the codes to process each row returned by the cursor takes place. This code block changes according to your reason to create and use a cursor. I placed an EXEC call for a sql stored procedure and an UPDATE sql statement here in order to show as a sample.

The most important thing to care for the inside codes of the WHILE code block is the last code statement FETCH NEXT command is recalled to get the next row from the return cursor data set.

After all the records are processed the @@FETCH_STATUS parameter returns -1, so the cursor can be now closed with the CLOSE CURSOR command. CLOSE CURSOR releases the current result set. And the DEALLOCATE CURSOR command releases the last cursor reference.

Here you can find the full sql cursor example code used in this article for explaining the t-sql cursors in SQL Server.
DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DuplicateId Int

SELECT @MergeDate = GetDate()


DECLARE merge_cursor CURSOR FAST_FORWARD FOR SELECT MasterCustomerId, DuplicateCustomerId FROM DuplicateCustomers WHERE IsMerged = 0

OPEN merge_cursor

FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId

WHILE @@FETCH_STATUS = 0
BEGIN
EXEC MergeDuplicateCustomers @MasterId, @DuplicateId

UPDATE DuplicateCustomers
SET
IsMerged = 1,
MergeDate = @MergeDate
WHERE
MasterCustomerId = @MasterId AND
DuplicateCustomerId = @DuplicateId

FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId
END

CLOSE merge_cursor
DEALLOCATE merge_cursor

Friday, 8 June 2012

Finding Duplicates with SQL

Here's a handy query for finding duplicates in a table. Suppose you want to find all email addresses in a table that exist more than once:
SELECT email, 
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

You could also use this technique to find rows that occur exactly once:
SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

Thursday, 3 May 2012

String Functions in MySql

Table 12.7. String Operators





























































































































































































































NameDescription
ASCII()Return numeric value of left-most character
BIN()Return a string representation of the argument
BIT_LENGTH()Return length of argument in bits
CHAR_LENGTH()Return number of characters in argument
CHAR()Return the character for each integer passed
CHARACTER_LENGTH()A synonym for CHAR_LENGTH()
CONCAT_WS()Return concatenate with separator
CONCAT()Return concatenated string
ELT()Return string at index number
EXPORT_SET()Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string
FIELD()Return the index (position) of the first argument in the subsequent arguments
FIND_IN_SET()Return the index position of the first argument within the second argument
FORMAT()Return a number formatted to specified number of decimal places
HEX()Return a hexadecimal representation of a decimal or string value
INSERT()Insert a substring at the specified position up to the specified number of characters
INSTR()Return the index of the first occurrence of substring
LCASE()Synonym for LOWER()
LEFT()Return the leftmost number of characters as specified
LENGTH()Return the length of a string in bytes
LIKESimple pattern matching
LOAD_FILE()Load the named file
LOCATE()Return the position of the first occurrence of substring
LOWER()Return the argument in lowercase
LPAD()Return the string argument, left-padded with the specified string
LTRIM()Remove leading spaces
MAKE_SET()Return a set of comma-separated strings that have the corresponding bit in bits set
MATCHPerform full-text search
MID()Return a substring starting from the specified position
NOT LIKENegation of simple pattern matching
NOT REGEXPNegation of REGEXP
OCTET_LENGTH()A synonym for LENGTH()
ORD()Return character code for leftmost character of the argument
POSITION()A synonym for LOCATE()
QUOTE()Escape the argument for use in an SQL statement
REGEXPPattern matching using regular expressions
REPEAT()Repeat a string the specified number of times
REPLACE()Replace occurrences of a specified string
REVERSE()Reverse the characters in a string
RIGHT()Return the specified rightmost number of characters
RLIKESynonym for REGEXP
RPAD()Append string the specified number of times
RTRIM()Remove trailing spaces
SOUNDEX()Return a soundex string
SOUNDS LIKECompare sounds
SPACE()Return a string of the specified number of spaces
STRCMP()Compare two strings
SUBSTR()Return the substring as specified
SUBSTRING_INDEX()Return a substring from a string before the specified number of occurrences of the delimiter
SUBSTRING()Return the substring as specified
TRIM()Remove leading and trailing spaces
UCASE()Synonym for UPPER()
UNHEX()Convert each pair of hexadecimal digits to a character
UPPER()Convert to uppercase

String-valued functions return NULL if the length of the result would be greater than the value of the max_allowed_packet system variable. See Section 8.9.2, “Tuning Server Parameters”.

For functions that operate on string positions, the first position is numbered 1.

For functions that take length arguments, noninteger arguments are rounded to the nearest integer.


  • ASCII(str)

    Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII() works for 8-bit characters.
    mysql> SELECT ASCII('2');
    -> 50
    mysql> SELECT ASCII(2);
    -> 50
    mysql> SELECT ASCII('dx');
    -> 100

    See also the ORD() function.

  • BIN(N)

    Returns a string representation of the binary value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,2). Returns NULL if N is NULL.
    mysql> SELECT BIN(12);
    -> '1100'


  • BIT_LENGTH(str)

    Returns the length of the string str in bits.
    mysql> SELECT BIT_LENGTH('text');
    -> 32


  • CHAR(N,... [USING charset_name])

    CHAR() interprets each argument N as an integer and returns a string consisting of the characters given by the code values of those integers. NULL values are skipped.
    mysql> SELECT CHAR(77,121,83,81,'76');
    -> 'MySQL'
    mysql> SELECT CHAR(77,77.3,'77.3');
    -> 'MMM'

    CHAR() arguments larger than 255 are converted into multiple result bytes. For example, CHAR(256) is equivalent to CHAR(1,0), and CHAR(256*256) is equivalent to CHAR(1,0,0):
    mysql> SELECT HEX(CHAR(1,0)), HEX(CHAR(256));
    +----------------+----------------+
    | HEX(CHAR(1,0)) | HEX(CHAR(256)) |
    +----------------+----------------+
    | 0100 | 0100 |
    +----------------+----------------+
    mysql> SELECT HEX(CHAR(1,0,0)), HEX(CHAR(256*256));
    +------------------+--------------------+
    | HEX(CHAR(1,0,0)) | HEX(CHAR(256*256)) |
    +------------------+--------------------+
    | 010000 | 010000 |
    +------------------+--------------------+

    By default, CHAR() returns a binary string. To produce a string in a given character set, use the optional USING clause:
    mysql> SELECT CHARSET(CHAR(0x65)), CHARSET(CHAR(0x65 USING utf8));
    +---------------------+--------------------------------+
    | CHARSET(CHAR(0x65)) | CHARSET(CHAR(0x65 USING utf8)) |
    +---------------------+--------------------------------+
    | binary | utf8 |
    +---------------------+--------------------------------+

    If USING is given and the result string is illegal for the given character set, a warning is issued. Also, if strict SQL mode is enabled, the result from CHAR() becomes NULL.

  • CHAR_LENGTH(str)

    Returns the length of the string str, measured in characters. A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

  • CHARACTER_LENGTH(str)

    CHARACTER_LENGTH() is a synonym for CHAR_LENGTH().

  • CONCAT(str1,str2,...)

    Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent binary string form; if you want to avoid that, you can use an explicit type cast, as in this example:
    SELECT CONCAT(CAST(int_col AS CHAR), char_col);

    CONCAT() returns NULL if any argument is NULL.
    mysql> SELECT CONCAT('My', 'S', 'QL');
    -> 'MySQL'
    mysql> SELECT CONCAT('My', NULL, 'QL');
    -> NULL
    mysql> SELECT CONCAT(14.3);
    -> '14.3'

    For quoted strings, concatenation can be performed by placing the strings next to each other:
    mysql> SELECT 'My' 'S' 'QL';
    -> 'MySQL'


  • CONCAT_WS(separator,str1,str2,...)

    CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is NULL, the result is NULL.
    mysql> SELECT CONCAT_WS(',','First name','Second name','Last Name');
    -> 'First name,Second name,Last Name'
    mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name');
    -> 'First name,Last Name'

    CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

  • ELT(N,str1,str2,str3,...)

    Returns str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments. ELT() is the complement of FIELD().
    mysql> SELECT ELT(1, 'ej', 'Heja', 'hej', 'foo');
    -> 'ej'
    mysql> SELECT ELT(4, 'ej', 'Heja', 'hej', 'foo');
    -> 'foo'


  • EXPORT_SET(bits,on,off[,separator[,number_of_bits]])

    Returns a string such that for every bit set in the value bits, you get an on string and for every bit not set in the value, you get an off string. Bits in bits are examined from right to left (from low-order to high-order bits). Strings are added to the result from left to right, separated by the separator string (the default being the comma character “,”). The number of bits examined is given by number_of_bits, which has a default of 64 if not specified. number_of_bits is silently clipped to 64 if larger than 64. It is treated as an unsigned integer, so a value of –1 is effectively the same as 64.
    mysql> SELECT EXPORT_SET(5,'Y','N',',',4);
    -> 'Y,N,Y,N'
    mysql> SELECT EXPORT_SET(6,'1','0',',',10);
    -> '0,1,1,0,0,0,0,0,0,0'


  • FIELD(str,str1,str2,str3,...)

    Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

    If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.

    If str is NULL, the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT().
    mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
    -> 2
    mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
    -> 0


  • FIND_IN_SET(str,strlist)

    Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.
    mysql> SELECT FIND_IN_SET('b','a,b,c,d');
    -> 2


  • FORMAT(X,D)

    Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.
    mysql> SELECT FORMAT(12332.123456, 4);
    -> '12,332.1235'
    mysql> SELECT FORMAT(12332.1,4);
    -> '12,332.1000'
    mysql> SELECT FORMAT(12332.2,0);
    -> '12,332'


  • HEX(str), HEX(N)

    For a string argument str, HEX() returns a hexadecimal string representation of str where each character in str is converted to two hexadecimal digits. The inverse of this operation is performed by the UNHEX() function.

    For a numeric argument N, HEX() returns a hexadecimal string representation of the value of N treated as a longlong (BIGINT) number. This is equivalent to CONV(N,10,16). The inverse of this operation is performed by CONV(HEX(N),16,10).
    mysql> SELECT 0x616263, HEX('abc'), UNHEX(HEX('abc'));
    -> 'abc', 616263, 'abc'
    mysql> SELECT HEX(255), CONV(HEX(255),16,10);
    -> 'FF', 255


  • INSERT(str,pos,len,newstr)

    Returns the string str, with the substring beginning at position pos and len characters long replaced by the string newstr. Returns the original string if pos is not within the length of the string. Replaces the rest of the string from position pos if len is not within the length of the rest of the string. Returns NULL if any argument is NULL.
    mysql> SELECT INSERT('Quadratic', 3, 4, 'What');
    -> 'QuWhattic'
    mysql> SELECT INSERT('Quadratic', -1, 4, 'What');
    -> 'Quadratic'
    mysql> SELECT INSERT('Quadratic', 3, 100, 'What');
    -> 'QuWhat'

    This function is multi-byte safe.

  • INSTR(str,substr)

    Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the order of the arguments is reversed.
    mysql> SELECT INSTR('foobarbar', 'bar');
    -> 4
    mysql> SELECT INSTR('xbar', 'foobar');
    -> 0

    This function is multi-byte safe, and is case sensitive only if at least one argument is a binary string.

  • LCASE(str)

    LCASE() is a synonym for LOWER().

  • LEFT(str,len)

    Returns the leftmost len characters from the string str, or NULL if any argument is NULL.
    mysql> SELECT LEFT('foobarbar', 5);
    -> 'fooba'


  • LENGTH(str)

    Returns the length of the string str, measured in bytes. A multi-byte character counts as multiple bytes. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
    mysql> SELECT LENGTH('text');
    -> 4


  • LOAD_FILE(file_name)

    Reads the file and returns the file contents as a string. To use this function, the file must be located on the server host, you must specify the full path name to the file, and you must have the FILE privilege. The file must be readable by all and its size less than max_allowed_packet bytes. If the secure_file_priv system variable is set to a nonempty directory name, the file to be loaded must be located in that directory.

    If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL.

    As of MySQL 5.1.6, the character_set_filesystem system variable controls interpretation of file names that are given as literal strings.
    mysql> UPDATE t
    SET blob_col=LOAD_FILE('/tmp/picture')
    WHERE id=1;


  • LOCATE(substr,str), LOCATE(substr,str,pos)

    The first syntax returns the position of the first occurrence of substring substr in string str. The second syntax returns the position of the first occurrence of substring substr in string str, starting at position pos. Returns 0 if substr is not in str.
    mysql> SELECT LOCATE('bar', 'foobarbar');
    -> 4
    mysql> SELECT LOCATE('xbar', 'foobar');
    -> 0
    mysql> SELECT LOCATE('bar', 'foobarbar', 5);
    -> 7

    This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.

  • LOWER(str)

    Returns the string str with all characters changed to lowercase according to the current character set mapping. The default is latin1 (cp1252 West European).
    mysql> SELECT LOWER('QUADRATICALLY');
    -> 'quadratically'

    LOWER() (and UPPER()) are ineffective when applied to binary strings (BINARY, VARBINARY, BLOB). To perform lettercase conversion, convert the string to a nonbinary string:
    mysql> SET @str = BINARY 'New York';
    mysql> SELECT LOWER(@str), LOWER(CONVERT(@str USING latin1));
    +-------------+-----------------------------------+
    | LOWER(@str) | LOWER(CONVERT(@str USING latin1)) |
    +-------------+-----------------------------------+
    | New York | new york |
    +-------------+-----------------------------------+

    This function is multi-byte safe.

  • LPAD(str,len,padstr)

    Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.
    mysql> SELECT LPAD('hi',4,'??');
    -> '??hi'
    mysql> SELECT LPAD('hi',1,'??');
    -> 'h'


  • LTRIM(str)

    Returns the string str with leading space characters removed.
    mysql> SELECT LTRIM(' barbar');
    -> 'barbar'

    This function is multi-byte safe.

  • MAKE_SET(bits,str1,str2,...)

    Returns a set value (a string containing substrings separated by “,” characters) consisting of the strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, and so on. NULL values in str1, str2, ... are not appended to the result.
    mysql> SELECT MAKE_SET(1,'a','b','c');
    -> 'a'
    mysql> SELECT MAKE_SET(1 | 4,'hello','nice','world');
    -> 'hello,world'
    mysql> SELECT MAKE_SET(1 | 4,'hello','nice',NULL,'world');
    -> 'hello'
    mysql> SELECT MAKE_SET(0,'a','b','c');
    -> ''


  • MID(str,pos,len)

    MID(str,pos,len) is a synonym for SUBSTRING(str,pos,len).

  • OCTET_LENGTH(str)

    OCTET_LENGTH() is a synonym for LENGTH().

  • ORD(str)

    If the leftmost character of the string str is a multi-byte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula:
      (1st byte code)
    + (2nd byte code * 256)
    + (3rd byte code * 256

    2
    ) ...

    If the leftmost character is not a multi-byte character, ORD() returns the same value as the ASCII() function.
    mysql> SELECT ORD('2');
    -> 50


  • POSITION(substr IN str)

    POSITION(substr IN str) is a synonym for LOCATE(substr,str).

  • QUOTE(str)

    Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (“\”), single quote (“'”), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.
    mysql> SELECT QUOTE('Don\'t!');
    -> 'Don\'t!'
    mysql> SELECT QUOTE(NULL);
    -> NULL

    For comparison, see the quoting rules for literal strings and within the C API in Section 9.1.1, “String Literals”, and Section 21.9.3.53, “mysql_real_escape_string()”.

  • REPEAT(str,count)

    Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty string. Returns NULL if str or count are NULL.
    mysql> SELECT REPEAT('MySQL', 3);
    -> 'MySQLMySQLMySQL'


  • REPLACE(str,from_str,to_str)

    Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.
    mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

    This function is multi-byte safe.

  • REVERSE(str)

    Returns the string str with the order of the characters reversed.
    mysql> SELECT REVERSE('abc');
    -> 'cba'

    This function is multi-byte safe.

  • RIGHT(str,len)

    Returns the rightmost len characters from the string str, or NULL if any argument is NULL.
    mysql> SELECT RIGHT('foobarbar', 4);
    -> 'rbar'

    This function is multi-byte safe.

  • RPAD(str,len,padstr)

    Returns the string str, right-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.
    mysql> SELECT RPAD('hi',5,'?');
    -> 'hi???'
    mysql> SELECT RPAD('hi',1,'?');
    -> 'h'

    This function is multi-byte safe.

  • RTRIM(str)

    Returns the string str with trailing space characters removed.
    mysql> SELECT RTRIM('barbar ');
    -> 'barbar'

    This function is multi-byte safe.

  • SOUNDEX(str)

    Returns a soundex string from str. Two strings that sound almost the same should have identical soundex strings. A standard soundex string is four characters long, but the SOUNDEX() function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a standard soundex string. All nonalphabetic characters in str are ignored. All international alphabetic characters outside the A-Z range are treated as vowels.

    Important

    When using SOUNDEX(), you should be aware of the following limitations:




    • This function, as currently implemented, is intended to work well with strings that are in the English language only. Strings in other languages may not produce reliable results.

    • This function is not guaranteed to provide consistent results with strings that use multi-byte character sets, including utf-8.

      We hope to remove these limitations in a future release. See Bug #22638 for more information.



    mysql> SELECT SOUNDEX('Hello');
    -> 'H400'
    mysql> SELECT SOUNDEX('Quadratically');
    -> 'Q36324'


    Note

    This function implements the original Soundex algorithm, not the more popular enhanced version (also described by D. Knuth). The difference is that original version discards vowels first and duplicates second, whereas the enhanced version discards duplicates first and vowels second.


  • expr1 SOUNDS LIKE expr2

    This is the same as SOUNDEX(expr1) = SOUNDEX(expr2).

  • SPACE(N)

    Returns a string consisting of N space characters.
    mysql> SELECT SPACE(6);
    -> ' '


  • SUBSTR(str,pos), SUBSTR(str FROM pos), SUBSTR(str,pos,len), SUBSTR(str FROM pos FOR len)

    SUBSTR() is a synonym for SUBSTRING().

  • SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len)

    The forms without a len argument return a substring from string str starting at position pos. The forms with a len argument return a substring len characters long from string str, starting at position pos. The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning. A negative value may be used for pos in any of the forms of this function.

    For all forms of SUBSTRING(), the position of the first character in the string from which the substring is to be extracted is reckoned as 1.
    mysql> SELECT SUBSTRING('Quadratically',5);
    -> 'ratically'
    mysql> SELECT SUBSTRING('foobarbar' FROM 4);
    -> 'barbar'
    mysql> SELECT SUBSTRING('Quadratically',5,6);
    -> 'ratica'
    mysql> SELECT SUBSTRING('Sakila', -3);
    -> 'ila'
    mysql> SELECT SUBSTRING('Sakila', -5, 3);
    -> 'aki'
    mysql> SELECT SUBSTRING('Sakila' FROM -4 FOR 2);
    -> 'ki'

    This function is multi-byte safe.

    If len is less than 1, the result is the empty string.

  • SUBSTRING_INDEX(str,delim,count)

    Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.
    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
    -> 'www.mysql'
    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
    -> 'mysql.com'

    This function is multi-byte safe.

  • TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str), TRIM([remstr FROM] str)

    Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiers BOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are removed.
    mysql> SELECT TRIM(' bar ');
    -> 'bar'
    mysql> SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');
    -> 'barxxx'
    mysql> SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');
    -> 'bar'
    mysql> SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz');
    -> 'barx'

    This function is multi-byte safe.

  • UCASE(str)

    UCASE() is a synonym for UPPER().

  • UNHEX(str)

    For a string argument str, UNHEX(str) performs the inverse operation of HEX(str). That is, it interprets each pair of characters in the argument as a hexadecimal number and converts it to the character represented by the number. The return value is a binary string.
    mysql> SELECT UNHEX('4D7953514C');
    -> 'MySQL'
    mysql> SELECT 0x4D7953514C;
    -> 'MySQL'
    mysql> SELECT UNHEX(HEX('string'));
    -> 'string'
    mysql> SELECT HEX(UNHEX('1267'));
    -> '1267'

    The characters in the argument string must be legal hexadecimal digits: '0' .. '9', 'A' .. 'F', 'a' .. 'f'. If the argument contains any nonhexadecimal digits, the result is NULL:
    mysql> SELECT UNHEX('GG');
    +-------------+
    | UNHEX('GG') |
    +-------------+
    | NULL |
    +-------------+

    A NULL result can occur if the argument to UNHEX() is a BINARY column, because values are padded with 0x00 bytes when stored but those bytes are not stripped on retrieval. For example, '41' is stored into a CHAR(3) column as '41 ' and retrieved as '41' (with the trailing pad space stripped), so UNHEX() for the column value returns 'A'. By contrast '41' is stored into a BINARY(3) column as '41\0' and retrieved as '41\0' (with the trailing pad 0x00 byte not stripped). '\0' is not a legal hexadecimal digit, so UNHEX() for the column value returns NULL.

    For a numeric argument N, the inverse of HEX(N) is not performed by UNHEX(). Use CONV(HEX(N),16,10) instead. See the description of HEX().

  • UPPER(str)

    Returns the string str with all characters changed to uppercase according to the current character set mapping. The default is latin1 (cp1252 West European).
    mysql> SELECT UPPER('Hej');
    -> 'HEJ'

    See the description of LOWER() for information that also applies to UPPER(), such as information about how to perform lettercase conversion of binary strings (BINARY, VARBINARY, BLOB) for which these functions are ineffective.

    This function is multi-byte safe.


Remove all special characters from data stored in MYSQL

Remove all special characters from data stored in MYSQL.:  ~!@#$%*()_+{}[];':"<>?
SELECT * FROM Film where REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(Film.name,':',''),'~',''),'!',''),'@',''),'#',''),'$',''),'%',''),'*',''),'(',''),')',''),'_',''),'+',''),
'{',''),'}',''),'[',''),']',''),';',''),'''',''),':',''),'"',''),'<',''),'>',''),'?','') = ? or

SELECT * FROM Film where REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(Film.name,':',''),'~',''),'!',''),'@',''),'#',''),'$',''),'%',''),'*',''),'(',''),')',''),'_',''),
'+',''),'{',''),'}',''),'[',''),']',''),';',''),'''',''),':',''),'"',''),'<',''),'>',''),'?',''),' ','') = ?

Friday, 17 February 2012

Connection String C# - VB.NET

Using C#:

using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString = "Data Source=(local);" +
"Initial Catalog=mySQLServerDBName;" +
"Integrated Security=SSPI";
oSQLConn.Open();


Using VB.NET:

Imports System.Data.SqlClient
...
Dim oSQLConn As SqlConnection = New SqlConnection()
oSQLConn.ConnectionString = "Data Source=(local);" & _
"Initial Catalog=mySQLServerDBName;" & _
"Integrated Security=SSPI"
oSQLConn.Open()


If connection to a remote server (via IP address):

oSQLConn.ConnectionString = "Network Library=DBMSSOCN;" & _
"Data Source=xxx.xxx.xxx.xxx,1433;" & _
"Initial Catalog=mySQLServerDBName;" & _
"User ID=myUsername;" & _
"Password=myPassword"
Where:
- "Network Library=DBMSSOCN" tells SqlConnection to use TCP/IP Q238949
- xxx.xxx.xxx.xxx is an IP address.
- 1433 is the default port number for SQL Server.  Q269882 and Q287932
- You can also add "Encrypt=yes" for encryption


 OLE DB .NET Data Provider (System.Data.OleDb)
The OLE DB .NET Data Provider uses native OLE DB through COM interop to enable data access. 


To use the OLE DB .NET Data Provider, you must also use an OLE DB provider (e.g.  SQLOLEDB, MSDAORA, or Microsoft.JET.OLEDB.4.0).

For IBM AS/400 OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=IBMDA400.DataSource.1;" & _
"Data source=myAS400DbName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For JET OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\myPath\myJet.mdb;" & _
"User ID=Admin;" & _
"Password="
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For Oracle OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=OraOLEDB.Oracle;" & _
"Data Source=MyOracleDB;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For SQL Server OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=sqloledb;" & _
"Data Source=myServerName;" & _
"Initial Catalog=myDatabaseName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For Sybase ASE OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=Sybase ASE OLE DB Provider;" & _
"Data Source=MyDataSourceName;" & _
"Server Name=MyServerName;" & _
"Database=MyDatabaseName;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()
For more information, see:  System.Data.OleDb Namespace and .NET Data Providers


 ODBC .NET Data Provider (System.Data.ODBC)
The ODBC .NET Data Provider is an add-on component to the .NET 1.0 Framework SDK. It provides access to native ODBC drivers the same way the OLE DB .NET Data Provider provides access to native OLE DB providers.


For SQL Server ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={SQL Server};" & _
"Server=MySQLServerName;" & _
"Database=MyDatabaseName;" & _
"Uid=MyUsername;" & _
"Pwd=MyPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Oracle ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft ODBC for Oracle};" & _
"Server=OracleServer.world;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Access (JET) ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=c:\somepath\mydb.mdb;" & _
"Uid=Admin;" & _
"Pwd="
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Sybase System 11 ODBC Driver

// C#
string myConnStr = "Driver={Sybase System 11};" +
"SRVR=mySybaseServerName;" +
"DB=myDatabaseName;" +
"UID=myUsername;" +
"PWD=myPassword";
OdbcConnection myConnection = new OdbcConnection(myConnStr);
myConnection.Open();


For all other ODBC Drivers

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = "Dsn=myDsn;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()
For more information, see:  ODBC .Net Data Provider


 .NET Framework Data Provider for Oracle (System.Data.OracleClient)
The .NET Framework Data Provider for Oracle is an add-on component to the .NET Framework that provides access to an Oracle database using the Oracle Call Interface (OCI) as provided by Oracle Client software. 


Using C#:

using System.Data.OracleClient;

OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "Data Source=Oracle8i;" +
"Integrated Security=SSPI";
oOracleConn.Open();


Using VB.NET:

Imports System.Data.OracleClient

Dim oOracleConn As OracleConnection = New OracleConnection()
oOracleConn.ConnectionString = "Data Source=Oracle8i;" & _
"Integrated Security=SSPI";
oOracleConn.Open()
Note: You must have the Oracle 8i Release 3 (8.1.7) Client or later installed in order for this provider to work correctly.


Note: You must have the RTM version of the .NET Framework installed in order for this provider to work correctly.

Note: There are known Oracle 7.3, Oracle 8.0, and Oracle9i client and server problems in this beta release. The server-side issues should be resolved in the final release of the product.  However, Oracle 7.3 client will not be supported.

 MySQL .NET Native Provider
The MySQL .NET Native Provider is an add-on component to the .NET Framework that allows you to access the MySQL database through the native protocol, without going through OLE DB.


Using C#

using EID.MySqlClient;

MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "Data Source=localhost;" +
"Database=mySQLDatabase;" +
"User ID=myUsername;" +
"Password=myPassword;" +
"Command Logging=false";
oMySqlConn.Open();


Using VB.NET

Imports EID.MySqlClient

Dim oMySqlConn As MySqlConnection = New MySqlConnection()
oMySqlConn.ConnectionString = "Data Source=localhost;"  & _
"Database=mySQLDatabase;"  & _
"User ID=myUsername;"  & _
"Password=myPassword;"  & _
"Command Logging=false"
oMySqlConn.Open()

Table of Connection Strings
























































DBConnection String
Access

Access ODBC Connection String Driver


{Microsoft Access Driver (*.mdb)};Dbq=C:\demo.mdb;Uid=Admin;Pwd=;

Access OLEDB Connection String Driver


Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\directory\demo.mdb;User Id=admin;Password=;
DB2

DB2 ODBC Connection String


driver={IBM DB2 ODBC DRIVER};Database=demodb;hostname=myservername;port=myPortNum;protocol=TCPIP; uid=myusername; pwd=mypasswd

DB2 OLEDB Connection String


Provider=IBMDADB2;Database=demodeb;HOSTNAME=myservername;PROTOCOL=TCPIP;PORT=50000;uid=myusername;pwd=mypasswd;
DBase

DBase ODBC Connection String


Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\directory;

DBase OLEDB Connection String


Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\directory;Extended Properties=dBASE IV;User ID=Admin;Password=
Excel

Excel ODBC Connection String


Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\directory;

Excel OLEDB Connection String


Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='"Excel 8.0;HDR=Yes;IMEX=1"'
Exchange

Exchange OLEDB Connection String


oConn.Provider = "EXOLEDB.DataSource" oConn.Open = "http://myServerName/myVirtualRootName"
Firebird

Firebird ODBC Connection String


DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=mypasswd;DBNAME=c:\directory\demo.fdb

Firebird OLEDB Connection String


User=SYSDBA;Password=mypasswd;Database=demo.fdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0
FoxPro

FoxPro ODBC Connection String


Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDB=c:\demo.dbc;Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=NO

FoxPro OLEDB Connection String


Provider=vfpoledb.1;Data Source=c:\directory\demo.dbc;Collating Sequence=machine
Informix

Informix ODBC Connection String


Driver={Informix-CLI 2.5 (32 Bit)};Server=demoservername;Database=demodb;Uid=myusername;Pwd=mypasswd

Informix OLEDB Connection String


Provider=Ifxoledbc.2;User ID=myusername;password=mypasswd;Data Source=demodb@demoservername;Persist Security Info=true
MySQL

MySQL ODBC Connection String


DRIVER={MySQL ODBC 3.51 Driver};SERVER=myservername;PORT=3306;DATABASE=mydemodb; USER=myusername;PASSWORD=mypasswd;OPTION=3;

MySQL OLEDB Connection String


Provider=MySQLProv;Data Source=mydemodb;User Id=myusername;Password=mypasswd;
Oracle

Oracle ODBC Connection String


Driver={Microsoft ODBC for Oracle};Server=myservername;Uid=myusername;Pwd=mypassword;

Oracle OLEDB Connection String


Provider=msdaora;Data Source=mydemodb;User Id=myusername;Password=mypasswd;

Oracle .Net Connection String


Data Source=mydemodb;User Id=myusername;Password=mypasswd;Integrated Security=no;
SQL Server

SQL Server ODBC Connection String - Database Login


Driver={SQL Server};Server=myservername;Database=mydemodb;Uid=myusername;Pwd=mypasswd;

SQL Server ODBC Connection String - Trusted Connection


Driver={SQL Server};Server=mysername;Database=mydemodb;Trusted_Connection=yes;

SQL Server OLEDB Connection String - Database Login


Provider=sqloledb;Data Source=myservername;Initial Catalog=mydemodb;User Id=myusername;Password=mypasswd;

SQL Server OLEDB Connection String - Trusted Connection


Provider=sqloledb;Data Source=myservername;Initial Catalog=mydemodb;Integrated Security=SSPI;

SQL Server .Net Connection String - Database Login


Server=myservername;Database=mydemodb;User ID=myusername;Password=mypasswd;Trusted_Connection=False

SQL Server .Net Connection String - Trusted Connection


Server=myservername;Database=mydemodb;Integrated Security=SSPI;
Sybase

Sybase ODBC Connection String


Driver={SYBASE ASE ODBC Driver};Srvr=myservername;Uid=myusername;Pwd=mypasswd

Sybase OLEDB Connection String


Provider=Sybase.ASEOLEDBProvider;Server Name=myservername,5000;Initial Catalog=mydemodb;User Id=myusername;Password=mypassword

Convert datatable to CSV format

public void CreateCSVfile(DataTable dtable, string strFilePath)
{

StreamWriter sw = new StreamWriter(strFilePath, false);
int icolcount = dtable.Columns.Count;
for (int i = 0; i < icolcount; i++)
{
sw.Write(dtable.Columns[i]);
if (i < icolcount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow drow in dtable.Rows)
{
for (int i = 0; i < icolcount; i++)
{
if (!Convert.IsDBNull(drow[i]))
{
sw.Write(drow[i].ToString());
}
if (i < icolcount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}

Connect C# to MySQL

Introduction


The purpose of this article is to show in a step by step manner how to use and connect C# with MySql using MySql Connect/NET. I will create simple examples about the DML (Insert, Update, Select, Delete) throughout the article to show how to query the database using C#, and in the end I will show you how to backup your database and save it in a .sql file from our application, and how to restore it back.

Getting Started


Downloading Connector/Net


First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.

Creating the Database


Now let's create the database, and the table that we are going to query from our application later on.

From the command line, we start by creating the database:
create database ConnectCsharpToMysql;

Then we select the database to use before creating the table:
use ConnectCsharpToMysql;

And we create the table that we will query from our application:
create table tableInfo
(
id INT NOT NULL AUTO INCREMENT,
name VARCHAR(30),
age INT,
PRIMARY KEY(id)
);

Using the Code


Adding Reference and Creating the MySQL Connector DLL from the Project


Before we start writing the code, we need to add the mysql Reference in our project. To do so, we right click our project name, and choose Add Reference:



Then we choose MySql.Data from the list:

AddReference 2

In order to use the application on other computers that don't have the connector installed, we will have to create a DLL from the reference. To do so, we right click the reference name in our project, and set the copy local to true in its properties:

Add dll

Creating the Class


It's always a better idea to create a new class for connecting to the database and to separate the actual code from the code that will access the database. This will help keep our code neat, easier to read and more efficient.

We will start by adding the MySql Connector library:
//Add MySql Library
using MySql.Data.MySqlClient;

Then declaring and initializing the variables that we will use:

  • connection: will be used to open a connection to the database.

  • server: indicates where our server is hosted, in our case, it's localhost.

  • database: is the name of the database we will use, in our case it's the database we already created earlier which is connectcsharptomysql.

  • uid: is our MySQL username.

  • password: is our MySQL password.

  • connectionString: contains the connection string to connect to the database, and will be assigned to the connection variable.


Our class will look as follows:
(Empty methods will be filled later on in this article.)
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;

//Constructor
public DBConnect()
{
Initialize();
}

//Initialize values
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

connection = new MySqlConnection(connectionString);
}

//open connection to database
private bool OpenConnection()
{
}

//Close connection
private bool CloseConnection()
{
}

//Insert statement
public void Insert()
{
}

//Update statement
public void Update()
{
}

//Delete statement
public void Delete()
{
}

//Select statement
public List <string> [] Select()
{
}

//Count statement
public int Count()
{
}

//Backup
public void Backup()
{
}

//Restore
public void Restore()
{
}
}

Opening and Closing the Connection


We should always open a connection before querying our table(s), and close it right after we're done, to release the resources and indicate that this connection is no longer needed.
Opening and closing a connection to the database is very simple, however, it's always better to use exception handling before opening a connection or closing it, to catch the errors and deal with them.
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;

case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}

//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}

Working with DML (Insert, Update, Select, Delete)


Usually, Insert, update and delete are used to write or change data in the database, while Select is used to read data.
For this reason, we have different types of methods to execute those queries.
The methods are the following:

  • ExecuteNonQuery: Used to execute a command that will not return any data, for example Insert, update or delete.

  • ExecuteReader: Used to execute a command that will return 0 or more records, for example Select.

  • ExecuteScalar: Used to execute a command that will return only 1 value, for example Select Count(*).


I will start with Insert, update and delete, which are the easiest. The process to successfully execute a command is as follows:

  1. Open connection to the database.

  2. Create a MySQL command.

  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.

  4. Execute the command.

  5. Close the connection.


//Insert statement
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";

//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);

//Execute command
cmd.ExecuteNonQuery();

//close connection
this.CloseConnection();
}
}

//Update statement
public void Update()
{
string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";

//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;

//Execute query
cmd.ExecuteNonQuery();

//close connection
this.CloseConnection();
}
}

//Delete statement
public void Delete()
{
string query = "DELETE FROM tableinfo WHERE name='John Smith'";

if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}

To execute a Select statement, we add a few more steps, and we use the ExecuteReader method that will return a dataReader object to read and store the data or records.

  1. Open connection to the database.

  2. Create a MySQL command.

  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.

  4. Create a MySqlDataReader object to read the selected records/data.

  5. Execute the command.

  6. Read the records and display them or store them in a list.

  7. Close the data reader.

  8. Close the connection.


//Select statement
public List< string >[] Select()
{
string query = "SELECT * FROM tableinfo";

//Create a list to store the result
List< string >[] list = new List< string >[3];
list[0] = new List< string >();
list[1] = new List< string >();
list[2] = new List< string >();

//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();

//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["name"] + "");
list[2].Add(dataReader["age"] + "");
}

//close Data Reader
dataReader.Close();

//close Connection
this.CloseConnection();

//return list to be displayed
return list;
}
else
{
return list;
}
}

Sometimes, a command will always return only one value, like for example if we want to count the number of records, we have been using Select Count(*) from tableinfo;, in this case, we will have to use the method ExecuteScalar that will return one value.

The process to successfully run and ExecuteScalar is as follows:

  1. Open connection to the database.

  2. Create a MySQL command.

  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.

  4. Execute the command.

  5. Parse the result if necessary.

  6. Close the connection.


//Count statement
public int Count()
{
string query = "SELECT Count(*) FROM tableinfo";
int Count = -1;

//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);

//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");

//close Connection
this.CloseConnection();

return Count;
}
else
{
return Count;
}
}

Backup and Restore the Database


Before I show you how to backup the database from our application, I will explain a little bit about processes, commands, arguments and the input and output.
Usually, to backup a MySQL database from the command line, we write the following:
mysqldump -u username -p password -h localhost ConnectCsharpToMysql > "C:\Backup.sql"

and to restore it, we write:
mysql -u username -p password -h localhost ConnectCsharpToMysql < "C:\Backup.sql"

The following commands can be divided as such:

  • mysql and mysqldump are the filename or the executable file.

  • -u username -p password -h localhost are the arguments.

  • > "C:\Backup.sql" is where the output is directed.

  • < "C:\Backup.sql" is where the input is directed.


Now that we know how the command is divided, we can start implementing it in our application.

In C# and .NET applications, starting a process is easy. First we add the library:
using System.Diagnostics;

Then we launch an application, such as Internet Explorer:
Process.Start("IExplore.exe");

ProcessStartInfo is used in conjunction with Process, to setup the process before it starts.
For example, to start Internet Explorer with arguments, we write the following:
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "IExplore.exe";
psi.Arguments = "www.codeproject.com";
Process.Start(psi);

To write our output to a file or read our input, we can use the RedirectStandardInput and RedirectStandardOutput properties in the ProcessStartInfo component to cause the process to get input from or return output to a file or other device. If we use the StandardInput or StandardOutput properties on the Process component, we must first set the corresponding value on the ProcessStartInfo property. Otherwise, the system throws an exception when we read or write to the stream.

Now back to our application, to backup the database, we will have to set the RedirectStandardOutput to true, and read the output from the process into a string and save it to a file.
//Backup
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;

//Save file to C:\ with the current date as a filename
string path;
path = "C:\\MySqlBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;

Process process = Process.Start(psi);

string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}

To restore the database, we read the .sql file and store it in a string, then set the RedirectStandardInput property to true, and write the input from the string to the process.
//Restore
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;

Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to Restore!");
}
}

Conclusion


In this article, I demonstrated how to connect C# to MySQL and query the tables using simple examples for the insert, update, delete and select statements.
Also, and because it's not widely available over the internet, I decided to demonstrate how to backup and restore a MySQL database from the C# application.

How to connect to MySQL 5.0. via C# .Net and the MySql Connector/Net



  • First, you need to install the mysql connector/net, it is located at: http://dev.mysql.com/downloads/connector/net/1.0.html


  • Next create a new project


  • Next add reference to: MySql.Data


  • Next add "using MySql.Data.MySqlClient;"


  • Finally add the following code to your application:


private void button1_Click(object sender, System.EventArgs e)
{
string MyConString = "SERVER=localhost;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
}

Configure Microsoft SQL Server for Mixed Mode Authentication

SQL Server uses two phase security authentication scheme. The user is first authenticated to the server. Once the user is "in" the server, access can be granted to the individual databases. SQL server stores all login information with in the master database.

There are two authentication methods in use.

  • Windows authentication mode

  • Mixed mode.


This article descibes how to setup mixed mode authentication, also known as SQL Authentication, in Microsoft SQL Server 2005 and SQL Server 2005 Express Edition.

SQL Server Authentication mode changed to Mixed modeNo GUI tool is available for SQL Server 2005 Express Edition to configure the server. You can do this manually. If your SQL server server is configured to use Windows NT authentication, you can change this to Mixed mode as below.

To verify the authentication mode, using SQL Server Management Studio Express, run the commands as follows.

EXEC xp_loginconfig 'login mode'


The optional server logins are useful when Windows authentication is inappropriate or unavailable. Implementing SQL server logins (mixed mode) will automatically create an sa user, who will be the member of the sysadmin fixed server role and have all rights to the server. The first step is to change the login-mode.

Open registry editor (launch application %WINDIR%\regedit.exe or Run--> regedit) and go to HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer in the tree on the left.

SQL Server Login Mode Changed using Reistry editorOn the right, look for an entry named LoginMode. The default value, when installed is 1. Update it to 2. The next step is to restart the service.

Launch your Service Manager (Start -> Run -> Type services.msc) and look for a service named MSSQL Server (SQLEXPRESS). Restart the service. Alternatively you can stop and restart the service using SQL Server Surface Area Configuration Manager tool of SQL server 2005 which is available in the Configuration tools submenu.

We need to add a user with administrative privileges so that the database can be accessed from ASP.Net.

SQL Server Creating New userWe can create a new user using the management studio express edition as shown in the figure.

Under Object Explorer-->Security --> Logins --> right click to add a new user dialog box to appear. Enter the user name and select SQL Server Authentication, type in the LoginName and password and click OK to create the user. Other check boxes should not be cheked for SQL Server 2005 Express Edition. On selecting SQL Server Authentication, three check boxes will get active. They are:

  • Enforce password policy

  • Enforce password expiration

  • User must change password at next login


Just deselect the Enforce password policy and you are ready to click OK button.

You can run the following command to create the user in a Query Window:


exec sp_addlogin 'username', 'password'


Alternatively using the command prompt: login to SQL Server command prompt using the osql utility. SQL Server 2005 Express Edition is installed with the instance name SQLEXPRESS. Use the following command to login:

osql -E -S .\SQLEXPRESS


One the SQL-command prompt, execute the following?

1> exec sp_addlogin 'username', 'password'  
2> go
1> exec sp_addsrvroleadmin 'username', 'sysadmin'
// above command will not work with SQL Server 2005 express edition
2> go
1> quit


Replace the username and password but not forget the quotes. To verify, try login using the following on the command prompt:

osql -S .\SQLExpress -U username


Creating new userOne it is done , you have to add the specific user to the specific database by selecting the database and right click add new user to bring up a dialog box which makes available the existing users with logins.

Also sometimes a bug is caused while you uninstall and reinstall SQL server. To fix this error is relatively simple:

  • Locate the following folder(This is the location in vista):C:\Users\*YourUserName\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS

  • Delete the SQLEXPRESS Folder.

  • Start the SQL Server Configuration Manager

  • SQL Server will repopulate that folder.

SQL SERVER – 2008 – Copy Database With Data – Generate T-SQL For Inserting Data From One Table to Another Table

how to generate script for data from database as well as table. SQL Server 2008 has simplified everything.

Let us take a look at an example where we will generate script database. In our example, we will just take one table for convenience.

Right Click on Database >> Tasks >> Generate Scripts >>





This will pop up Generate SQL Server Scripts Wizards >> Click on Next >> Select Database >> This will bring up a screen that will suggest to Choose Script Option.



On Choose Script Option Screen of Script Wizard under section Table/View Options Look at Script Data row and Turn the Option to True.



The Next Screen will ask about object types. Select all the objects that are required in the generated script. Depending on the previous screen it will show few more screen requesting details about the objects required in script generation.





On the very last screen it will request output options. Select the desired output options of Script to file, Script to Clipboard or Script New Query Window.3



Clicking on Finish button will generate a review screen containing the required objects along with script generating data.





Clicking on Finish button one more time will generate the requested output.



Similarly, if you want to generate data for only one table, you can right click on the table and follow almost a similar wizard.

SQL SERVER – Change Password of SA Login Using Management Studio

Login into SQL Server using Windows Authentication.

In Object Explorer, open Security folder, open Logins folder. Right Click on SA account and go to Properties.



Change SA password, and confirm it. Click OK.



Make sure to restart the SQL Server and all its services and test new password by log into system using SA login and new password.