How to Execute SQL Statements Interactively

Suppose you’ve just started mysql. Now you want to send SQL statements to the MySQL server to be executed. To do this, just type them in, letting mysql know where each one ends. Or specify “one-liners” directly on the command line.

When you invoke mysql, it displays a mysql> prompt to tell you that it’s ready for input. To execute an SQL statement at the mysql> prompt, type it in, add a semicolon ( ; ) at the end to signify the end of the statement, and press Enter. An explicit statement terminator is necessary; mysql doesn’t interpret Enter as a terminator because you can enter a statement using multiple input lines. Continue reading

[Tutorial] Creating a Database and a Sample Table in MySQL

Use a CREATE DATABASE statement to create the database, a CREATE TABLE statement for each table, and INSERT statements to add rows to the tables.

The GRANT statement shown in previous post sets up privileges for accessing the cookbook database but does not create the database. This section shows how to do that, and also how to create a table and load it with the sample data used for examples in the following sections. Similar instructions apply for creating other tables used elsewhere in this book. Continue reading

[Tutorial] How To Create a New User and Grant Permissions in MySQL Database

In previous post we talked about MySQL Database. Now we need an account for connecting to MySQL server.

Use CREATE USER and GRANT statements to set up the account. Then use the account name and password to make connections to the server.

Connecting to a MySQL server requires a username and password. You may also need to specify the name of the host on which the server is running. If you don’t specify connection parameters explicitly, mysql assumes default values. For example, given no explicit hostname, mysql assumes that the server is running on the local host. Continue reading

Introduction to MySQL Database

The MySQL database system uses a client-server architecture. The server, mysqld, is the program that actually manipulates databases. To tell the server what to do, use a client program that communicates your intent by means of statements written in Structured Query Language (SQL).

Client programs are written for diverse purposes, but each interacts with the server by connecting to it, sending SQL statements to have database operations performed, and receiving the results.

Clients are installed locally on the machine from which you want to access MySQL, but the server can be installed anywhere, as long as clients can connect to it. Continue reading

How To Import the Regular Expression Library in Programming Language

To be able to use regular expressions in your application, you want to import the regular
expression library or namespace into your source code.

C#

using System.Text.RegularExpressions;

If you place the using statement at the top of your C# source file, you can reference the classes that provide regular expression functionality directly, without having to fully qualify them. For instance, you can write Regex() instead of System.Text.RegularExpressions.Regex() .  Continue reading

What is the difference between object, primitive and literal in JavaScript?

A JavaScript literal represents a value of a specific type, such as a quoted string (String), floating-point number (Number), or boolean (Boolean):

"this is a string"
1.45
true

A JavaScript primitive is an instance of a particular data type, and there are five such in the language: String, Number, Boolean, null , and undefined. The following are examples of JavaScript primitives:

"this is a string"
null

Of the primitive data types, three have complementary constructor objects: String, Number, and Boolean. These objects provide access to the built-in properties and methods that allow us to do more than simple assignment and subsequent access:

var str1 = "this is a string";
console.log(str1.length); // using String object's length property

It may seem as if we’re working with simple strings or numbers when we declare a variable:

var str1 = "this is a simple string";

However, we’re actually creating doorways into an extensive set of functionality. Without reliance on JavaScript objects, we can assign a string, number, or boolean value to a variable and then access it at a later time. However, if we want to do more with the variable, we’ll need to use the data type’s complementary JavaScript object and its properties.

As an example, if we want to see the length of a string, we’ll access the String object’s length property:

var str1 = "this is a simple string";
console.log(str1.length); // prints out 23 to browser console

Behind the scenes, when the code accesses a String object’s property on the literal, a new String object is created and its value is set to the value of the string contained in the variable. The length property is accessed and printed out, and the newly created String object is discarded.

JavaScript engines don’t have to actually create an object to wrap the primitive when you access object properties; they only have to emulate this type behavior.

There are exactly five primitive data types in JavaScript: string, number, boolean, null , and undefined. Only the string, number, and boolean data types have complementary constructor objects. The actual representation of strings, floating-point numbers, integers, and booleans are literals:

var str1 = "this is a simple string"; // the quoted string is the literal
var num1 = 1.45; // the value of 1.45 is the literal
var answer = true; // the values of true and false are boolean literals

We can create primitive boolean, string, and number variables either by using a literal representation or using the object without using the new operator:

var str1 = String("this is a simple string"); // primitive string
var num1 = Number(1.45); // primitive number
var bool1 = Boolean(true); // primitive boolean

To deliberately instantiate an object, use the new operator:

var str2 = new String("this is a simple string"); // String object instance
var num2 = new Number(1.45); // Number object instance
var bool2 = new Boolean(true); // primitive boolean

You can quickly tell the difference between a primitive and an object instance when you compare an object instance to a literal value using strict equality. For example, running the following code in a browser:

var str1 = String("string");
var num1 = Number(1.45);
var bool1 = Boolean(true);

if (str1 === "string") {
console.log('equal');
}

if (num1 === 1.45) {
console.log('equal');
}

if (bool1 === true) {
console.log('equal');
}

var str2 = new String("string");
var num2 = new Number(1.45);
var bool2 = new Boolean(true);

if (str2 === "string") {
console.log('equal');
} else {
console.log('not equal');
}

if (num2 === 1.45) {
console.log('equal');
} else {
console.log('not equal');
}

if (bool2 === true) {
console.log('equal');
} else {
console.log('not equal');
}

Results in the following print outs to the console :

equal
equal
equal
not equal
not equal
not equal

The primitive variables (those not created with new ) are strictly equal to the literals, while the object instances are not. Why are the primitive variables strictly equal to the literals? Because primitives are compared by value, and values are literals.

For the most part, JavaScript developers don’t directly create object instances for the three primitive data types. Developers just want a number, boolean, or string variable to act like a number, boolean, or string, rather than an object; we don’t need the enhanced functionality of the object. More importantly, when developers use strict equality or type checking in the code, they want a variable to match their expectations of data type, rather than be defined as “object”:

var num1 = 1.45;
var num2 = new Number(1.45);

console.log(typeof num1); // prints out number
console.log(typeof num2); // prints out object

Code validators, such as JSHint, output a warning if you instantiate a primitive data type object directly for just this reason.

String Slicing in Python Language

A slice is a span of items that are taken from a sequence. When you take a slice from a string, you get a span of characters from within the string. String slices are also called substrings.

To get a slice of a string, you write an expression in the following general format:

string[start : end]

In the general format, start is the index of the first character in the slice, and end is the index marking the end of the slice. The expression will return a string containing a copy of the characters from start up to (but not including) end . For example, suppose we have the following:

full_name = 'Patty Lynn Smith'
middle_name = full_name[6:10]

The second statement assigns the string ‘Lynn’ to the middle_name variable. If you leave out the start index in a slicing expression, Python uses 0 as the starting index. Here is an example:

full_name = 'Patty Lynn Smith'
first_name = full_name[:5]

The second statement assigns the string ‘Patty’ to first_name . If you leave out the end index in a slicing expression, Python uses the length of the string as the end index. Here is an example:

full_name = 'Patty Lynn Smith'
last_name = full_name[11:]

The second statement assigns the string ‘Smith’ to last_name . What do you think the following code will assign to the my_string variable?

full_name = 'Patty Lynn Smith'
my_string = full_name[:]

The second statement assigns the entire string ‘Patty Lynn Smith’ to my_string. The statement is equivalent to:

my_string = full_name[0 : len(full_name)]

The slicing examples we have seen so far get slices of consecutive characters from strings. Slicing expressions can also have step value, which can cause characters to be skipped in the string. Here is an example of code that uses a slicing expression with a step value:

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(letters[0:26:2])

The third number inside the brackets is the step value. A step value of 2, as used in this example, causes the slice to contain every second character from the specified range in the string. The code will print the following:

ACEGIKMOQSUWY

You can also use negative numbers as indexes in slicing expressions to reference positions relative to the end of the string. Here is an example:

full_name = 'Patty Lynn Smith'
last_name = full_name[-5:]

Recall that Python adds a negative index to the length of a string to get the position referenced by that index. The second statement in this code assigns the string ‘Smith’ to the last_name variable.

Invalid indexes do not cause slicing expressions to raise an exception. For example:

  • If the end index specifies a position beyond the end of the string, Python will use the length of the string instead.
  • If the start index specifies a position before the beginning of the string, Python will use 0 instead.
  • If the start index is greater than the end index, the slicing expression will return an empty string.

String Concatenation in Python Language

A common operation that performed on strings is concatenation, or appending one string to the end of another string. You have seen examples in earlier chapters that use the + operator to concatenate strings. The + operator produces a string that is the combination of the two strings used as its operands. The following interactive session demonstrates:

>>> message = 'Hello ' + 'world' [Enter]
>>> print(message) [Enter]
Hello world
>>>

Line 1 concatenates the strings ‘Hello’ and ‘world’ to produce the string ‘Hello world’. The string ‘Hello world’ is then assigned to the message variable. Line 2 prints the string that is referenced by the message variable. The output us shown in line 3.

Here is another interactive session that demonstrates concatenation:

>>> first_name = 'Emily' [Enter]
>>> last_name = 'Yeager' [Enter]
>>> full_name = first_name + ' ' + last_name [Enter]
>>> print(full_name) [Enter]
Emily Yeager
>>>

Line 1 assigns the string ‘Emily’ to the first_name variable. Line 2 assigns the string ‘Yeager’ to the last_name variable. Line 3 produces a string that is the concatenation of first_name , followed by a space, followed by last_name . The resulting string is assigned to the full_name variable. Line 4 prints the string referenced by full_name. The output is shown in line 5.

You can also use the += operator to perform concatenation. The following interactive session demonstrates:

>>> letters = 'abc' [Enter]
>>> letters += 'def' [Enter]
>>> print(letters) [Enter]
abcdef
>>>

The statement in line 2 performs string concatenation. It works the same as:

letters = letters + 'def'

After the statement in line 2 executes, the letters variable will reference the string ‘abcdef’ . Here is another example:

>>> name = 'Kelly' [Enter]      # name is 'Kelly'
>>> name += ' ' [Enter]         # name is 'Kelly '
>>> name += 'Yvonne' [Enter]    # name is 'Kelly Yvonne'
>>> name += ' ' [Enter]         # name is 'Kelly Yvonne '
>>> name += 'Smith' [Enter]     # name is 'Kelly Yvonne Smith'
>>> print(name) [Enter]
Kelly Yvonne Smith
>>>

Keep in mind that the operand on the left side of the += operator must be an existing variable. If you specify a nonexistent variable, an exception is raised.

[Python] Finding Items in Lists with the in Operator

In Python you can use the in operator to determine whether an item is contained in a list. Here is the general format of an expression written with the in operator to search for an item in a list:

item in list

In the general format, item is the item for which you are searching, and list is a list. The expression returns true if item is found in the list or false otherwise. Program 1-1 shows an example.

# This program demonstrates the in operator
# used with a list.

def main():
    # Create a list of product numbers.
    prod_nums = ['V475', 'F987', 'Q143', 'R688']

    # Get a product number to search for.
    search = input('Enter a product number: ')

    # Determine whether the product number is in the list.
    if search in prod_nums:
        print(search, 'was found in the list.')
    else:
        print(search, 'was not found in the list.')

# Call the main function.
main()

Below you can see program output:

Enter a product number: Q143 [Enter]
Q143 was found in the list.

Enter a product number: B000 [Enter]
B000 was not found in the list.

The program gets a product number from the user in line 9 and assigns it to the search variable. The if statement in line 12 determines whether search is in the prod_nums list.

You can use the not in operator to determine whether an item is not in a list. Here is an example:

if search not in prod_nums:
    print(search, 'was not found in the list.')
else:
    print(search, 'was found in the list.')

Now, question for you, dear reader. What will the following code display:

names = ['Jim', 'Jill', 'John', 'Jasmine']
if 'Jasmine' not in names:
    print('Cannot find Jasmine.')
else:
    print("Jasmine's family:")
    print(names)

 

Introduction to Lists in Python Language

A list is an object that contains multiple data items. Lists are mutable, which means that their contents can be changed during a program’s execution. Lists are dynamic data structures, meaning that items may be added to them or removed from them. You can use indexing, slicing, and various methods to work with lists in a program. Each item that is stored in a list is called an element. Here is a statement that creates a list of integers:

even_numbers = [2, 4, 6, 8, 10]

The items that are enclosed in brackets and separated by commas are the list elements. After this statement executes, the variable even_numbers will reference the list, as shown in Figure 7-1.

img

The following is another example:

names = ['Molly', 'Steven', 'Will', 'Alicia', 'Adriana']

This statement creates a list of five strings. After the statement executes, the name variable will reference the list as shown in Figure 7-2.

img

A list can hold items of different types, as shown in the following example:

info = ['Alicia', 27, 1550.87]

This statement creates a list containing a string, an integer, and a floating-point number. After the statement executes, the info variable will reference the list as shown in Figure 7-3.

img

You can use the print function to display an entire list, as shown here:

numbers = [22, 25, 29, 33]
print(numbers)

In this example, the print function will display the elements of the list like this:

numbers = [22, 25, 29, 33]

Python also has a built-in list() function that can convert certain types of objects to lists.

You can use a statement such as the following to convert the range function’s iterable object to a list:

numbers = list(range(5))

When this statement executes, the following things happen:

  • The range function is called with 5 passed as an argument. The function returns an iterable containing the values 0, 1, 2, 3, 4.
  • The iterable is passed as an argument to the list() function. The list() function
    returns the list [0, 1, 2, 3, 4] .
  • The list [0, 1, 2, 3, 4] is assigned to the numbers variable.

Here is another example:

numbers = list(range(1, 10, 2))

When you pass three arguments to the range function, the first argument is the starting value, the second argument is the ending limit, and the third argument is the step value. This statement will assign the list [1, 3, 5, 7, 9] to the numbers variable.