You are reading the article Learn The Implementation Of Db2 Cast With Examples updated in December 2023 on the website Minhminhbmm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Learn The Implementation Of Db2 Cast With Examples
Introduction to DB2 CASTDB2 CAST is a function available in DB2 that is used for explicit conversion of the data type of a particular value to another datatype. DB2 comes with the default facility of trying to convert the datatypes of the values if they are not mentioned properly to an expected data type value in all the functions and the instructions that are issued and where there is a necessity of doing so. This is called implicit casting or conversion of a datatype. In this article, we will study how we can convert the value of one data type to another with the help of the CAST() function available in DB2, the syntax of the CAST() function, and the implementation with the help of certain examples.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Syntax
CAST(any expression or value AS the required datatype)
In the above expression, the expression or value can be any field value of a particular table column or a constant value, or even a variable that holds a certain value. The required data type is the data type that you want the value mentioned as the expression to be converted to. We can specify any data type, we want the data to convert to such as int, string, etc.
Implicit casting in DB2 ExamplesConsider the following example where we are trying to add 6 integer value with ‘16’ string value using the plus(+) operator and retrieve the result –
6 + ’16’ as result ;
The execution of the above query statement gives the following output with the resultant value being an integer which is 22. Over here, DB2 firstly converted the string ‘16’ to an integer value and then went for doing the addition.
Let us consider one more example where we will be using the concatenation operator which is a string operator and works only with string. When we use the same values specified in the above example 6 and ‘16’ which are an integer and a string, using the following query statement –
The execution of the above query statement gives the following output with the resultant value being a string which is 616. Over here, DB2 firstly converted the integer 6 to string value and then goes for doing the concatenation.
Now, let us see, how we can cast the values explicitly using the CAST() function. If the values cannot be cast by the DB2 due to incompatible type of values, it throws an error saying as shown in the below image –
Now, let us try to convert a decimal value to an integer value using the DB2 CAST() function which will do explicit datatype conversion for us. Consider the following query statement where we are trying to convert a decimal number 14.562 to and integer value to get a rounded whole number. We can do this by using the following query statement with the CAST() function in it –
The output of the above query statement is a rounded integer value of 14.562 which is 14 as shown below –
Now, consider a decimal number 16.5454 which we want to cast to a decimal number itself but a lower scale value to it. We can even do this by using the CAST() function and our query statement, in this case, will look as follows –
CAST ( 16.5454 DEC (4,2)) AS result;
The output of the above query statement’s execution is as shown below with the number rounded and cast to a decimal value of two places after a decimal point has a different scale than the original one –
Let us try to convert a value of the TIMESTAMP datatype to the TIME datatype, in order to get only the time value in the output. We will convert the current timestamp value to time using the cast function in the following query statement to retrieve the current time value of the system –
CAST (CURRENT TIMESTAMP AS TIME) as result;
The execution of the above query statement gives the following result where we get the value of the current time of the system from the current TIMESTAMP value which is as shown below –
We can even convert the current timestamp value to the date datatype in order to retrieve today’s date of my system and using the following query statement and the CAST() function –
CAST (CURRENT TIMESTAMP AS DATE) as result;
The output of the execution of the above query statement is as shown below with the date value in it which is the current system date.
Let us try one last example where we will cast the value of string data type to a DATE datatype explicitly by using the CAST() function in DB2 RDBMS. Let us consider a random date value say ‘2030-01-27’. We will try to convert this string to DATE datatype by using the following query statement –
CAST(‘2030-01-27’ AS DATE) result;
The output of the execution of the above query statement in DB2 DBMS gives the following resultant value with the date specified being cast to a DATE data type as shown below –
ConclusionIN DB2 RDBMS, the datatypes are internally converted into required datatypes while using the functions and manipulations and while doing operations. However, if we want to explicitly convert a particular value to a required datatype then we can make use of the CAST() function to convert the value to a different datatype explicitly in DB2 RDBMS. We can convert the data type f the values to any in-built and user-defined datatype using the CAST() function.
Recommended ArticlesThis is a guide to DB2 CAST. Here we discuss how we can convert the value of one data type to another with the help of the CAST() function. You may also look at the following article to learn more –
You're reading Learn The Implementation Of Db2 Cast With Examples
Learn The Examples For Implementation
Introduction to PostgreSQL REGEXP_REPLACE
The regular expression is a sequence of characters, the short name for the list of strings. If any string matches with any of the strings, which is part of a list of the strings defined by the regular expression. PostgreSQL supports the regular expression, and the function provided by PostgreSQL is used to replace substrings with a new substring that matches a POSIX regular expression. The PostgreSQL REGEXP_REPLACE() function uses a POSIX regular expression pattern.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Syntax:
REGEXP_REPLACE(input_string, regex_pattern, replace_string,[, flags])Explanation:
input_string: This defines the input string in which replacement should be taken place for a specified pattern, a POSIX regular expression.
regex_pattern: This defines the POSIX regular expression to match the string.
flags: This flag is used to control the behavior of the REGEXP_REPLACE() function, This can have the value of one or more characters.
Replace_string: This string defines a string that replaces the substring, which matches the POSIX regular expression pattern.
Examples of PostgreSQL REGEXP_REPLACEHere are the following examples of implementing the PostgreSQL REGEXP_REPLACE function
Consider the following name format like the first name and then last name:
‘Jacob David’
Suppose we want to re-arrange the last name and the first name for purposes like the last name and then the first name. So, we can use the PostgreSQL REGEXP_REPLACE() function to do this as follows:
SELECT REGEXP_REPLACE('Jacob David', '(.*) (.*)', '2, 1');Illustrate the result of the above statement by using the following snapshot.
Example #2Example, to remove the string, consider we have a string in the following as follows:
"xyz54321ABC"Now, we will remove all alphabets characters from the above string by using the following statement:
SELECT REGEXP_REPLACE('xyz54321ABC', '[[:alpha:]]', '', 'g');Illustrate the result of the above statement by using the following snapshot.
Now, we will remove all digits from the above string by using the following statement:
SELECT REGEXP_REPLACE('xyz54321ABC', '[[:digit:]]', '', 'g');Illustrate the result of the above statement by using the following snapshot.
In the above examples, we have used the following regular expressions.
'[[:alpha:]]' '[[:digit:]]'Also, we have used the replacement string as ‘’ and the flag ‘g’ we have used to instruct the PostgreSQL REGEXP_REPLACE function to replace all of the occurrences of the matched string and not just the first occurrence.
Example #3Remove multiple occurrences of the spaces. Consider the following example, which removes more than one space that occurred in a string. Consider the following statement to do the same.
SELECT REGEXP_REPLACE('PostgreSQL is awesome database', '( ){2,}', ' ', 'g');Illustrate the result of the above statement by using the following snapshot.
Example #4We will create a table named ‘student’ by using the CREATE TABLE statement as follows:
create table student ( stud_id serial PRIMARY KEY, stud_fname VARCHAR(80) NOT NULL, stud_lname VARCHAR(80) NOT NULL );Now, we will insert some data into the student table by using the INSERT INTO statement as follows
INSERT INTO student(stud_fname,stud_lname) VALUES ('Smith','Johnson'), ('Williams','Jones'), ('Brown','Davis');Illustrate the above INSERT statement’s result using the following SQL statement and snapshot.
select * from student;Consider the following SQL statement where we are checking whether the stud_lname is having ‘Jo’ substring, and if it exists, then we replace it with ‘K.’
SELECT REGEXP_REPLACE(stud_lname , 'Jo', 'K') AS "New Name" FROM student;Also, consider the other example,
Consider the following SQL statement where we are checking whether the stud_lname is having ‘s’ substring, and if it exists, then we replace it with ‘K’
SELECT REGEXP_REPLACE(stud_lname , 's', 'K') AS "New Name" FROM student;Illustrate the result of the above SQL statement by using the following snapshot.
Advantages of using PostgreSQL REGEXP_REPLACE () function1. The PostgreSQL REGEXP_REPLACE () function supports various flags,
Consider examples like:
flag ‘i’ : match case-insensitively
flag ‘g’: search globally for each occurrence.
2. The PostgreSQL REGEXP_REPLACE() replaces all occurrences of the substring with the new string.
3. We can use The PostgreSQL REGEXP_REPLACE() function, the substring in variable length or dynamic strings.
ConclusionFrom the above article, we hope you understand how to use the PostgreSQL REGEXP_REPLACE() function and how the PostgreSQL REGEXP_REPLACE() function works. Also, we have added several examples of the PostgreSQL REGEXP_REPLACE() function to understand it in detail.
Recommended articlesWe hope that this EDUCBA information on “PostgreSQL REGEXP_REPLACE” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Learn The Examples And Advantages
Introduction to PostgreSQL STRING_AGG()
PostgreSQL supports various kinds of aggregate functions, The STRING_AGG() function is one of the aggregate functions which is used to concatenate the list of strings, and it will add a place to a delimiter symbol or a separator between all of the strings. The separator or a delimiter symbol will not be included at the end of the output string. The PostgreSQL STRING_AGG() function is supported by PostgreSQL 9.0 version, which performs the aggregate option related to the string. We can use various separators or delimiter symbols to concatenate the strings.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
SyntaxExplanation:
The STRING_AGG() function takes input ORDER BY clause is an optional and other two arguments as follows:
expression: This is a character string that is any valid expression.
separator/delimiter: This defines the separator/delimiter used for string concatenation.
The ORDER BY clause is optional and defines the order of concatenated string results.
The ORDER BY has the syntax as follows:
How does PostgreSQL STRING_AGG() function works?
The input expression needed should be a character string data type. We can also use other data types but only need to ensure that we have explicitly cast other data types to the character string data type.
The PostgreSQL STRING_AGG() returns us the result in string type.
The STRING_AGG() is generally used with the GROUP BY clause like we use other PostgreSQL aggregate functions such as MIN(), MAX(), AVG(), SUM(), COUNT(), etc.
Examples to Implement PostgreSQL STRING_AGG() functionWe will create a table named ‘student’ and ‘course’ by using the CREATE TABLE statement as follows:
STUDENT TABLE:
create table student ( stud_id serial PRIMARY KEY, stud_name VARCHAR(80) NOT NULL, stud_grade CHAR(1) NOT NULL, stud_country VARCHAR(80) NOT NULL, course_id int NOT NULL );COURSE TABLE:
create table course ( course_id serial PRIMARY KEY, course_name VARCHAR(80) NOT NULL );Now, we will insert some data into the ‘course’ table by using the INSERT INTO statement as follows:
INSERT INTO course(course_name) VALUES ('Computer'), ('Mechanical'), ('Civil'), ('Electrical');Illustrate the above INSERT statement’s result using the following SQL statement and snapshot.
select * from course; INSERT INTO student(stud_name,stud_grade,stud_country,course_id) VALUES ('Smith','A','USA',1), ('Johnson','B','USA',2), ('Williams','C','USA',3), ('Jones','C','Canada',1), ('Brown','B','Canada',2), ('Davis','A','Canada',3), ('Aarnav','A','India',1), ('Aarush','B','India',2), ('Aayush','C','India',3), ('Abdul','C','UAE',1), ('Ahmed','A','UAE',3), ('Ying', 'A','China',1), ('Yue','B','China',2), ('Feng', 'C','China',3), ('Mian','C','South Korea',1), ('Fei','B','South Korea',2), ('Hong','A','South Korea',3);Illustrate the above INSERT statement’s result using the following SQL statement and snapshot.
select * from student; SELECT c.course_name AS "course name", s.stud_name AS "student name" FROM course c RIGHT JOIN student s ON c.course_id = s.course_id ORDER BY 1;Illustrate the result of the above statement by using the following snapshot.
We can concatenate the student names by using the STRING_AGG() function by modifying the above SQL statement as follows:
SELECT crs.course_name AS "course name", string_agg(stud.stud_name, ', ') AS "student list" FROM course crs JOIN student stud ON crs.course_id = stud.course_id GROUP BY 1 ORDER BY 1;Illustrate the result of the above statement by using the following snapshot.
SELECT stud_grade, STRING_AGG(stud_name,', ') AS StudentsPerGrade FROM student GROUP BY stud_grade ORDER BY 1 ;Illustrate the result of the above statement by using the following snapshot.
In the above example, the resulting snapshot shows us the students concatenated by a comma separator with a similar grade obtained.
SELECT STRING_AGG(stud_name, ', ') AS "student_names", stud_country FROM student GROUP BY stud_country;Illustrate the result of the above statement by using the following snapshot.
In the above example, we observe that the code groups and concatenates all students from the same country, utilizing a comma separator.
Advantages
We can control the order of the result by using the ORDER BY clause.
The PostgreSQL STRING_AGG() function returns the result in string format.
We can use the STRING_AGG() function to concatenate all strings and add a delimiter symbol or separator between them.
The PostgreSQL STRING_AGG() supports various types of delimiter symbols or separators and does not include delimiter symbols or separators at the end of the string.
ConclusionFrom the above article, we hope you understand how to use the PostgreSQL STRING_AGG() function and how the PostgreSQL STRING_AGG() function works. Also, we have added several examples of the PostgreSQL STRING_AGG() function to understand it in detail.
Recommended ArticlesWe hope that this EDUCBA information on “PostgreSQL STRING_AGG()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
List Of The Filters Available In Angularjs With Examples
Introduction to AngularJS Filters
The filter is used to filter the elements. In other words filter in angular js is used to filter the element and object and returned the filtered items. Basically filter selects a subset from the array from the original array.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
comparator: This property is used to determining the value, it compares the expected value from the filtered expression and the actual value from the object array.
anyPropertyKey: This is a special property that is used to match the value against the given property. it has a default value as $.
arrayexpression: It takes the array on which we applied the filter.
expression: It is used to select the items from the array after the filter conditions are met.
Example of AngularJS Filters<script src= {{ x }} </div> angular.module(‘myApp’, []).controller( ‘namesCtrl’, function($scope) { $scope.names = [ ‘xyz’, ‘abc’, ‘uth’, ‘ert’, ‘opu’, ‘wrf’, ‘mkl’, ‘hgt’, ‘mnv’ ]; }); This will show the names contain “m” character filter.
Output:
List of the Filters available in AngularJSAngular js provide many built-in filters which are listed below.
uppercase: This filter is used to format the string to upper case.
lowercase: This filter is used to format the string to lowercase.
currency: This filter is used to format a number to the current format.
orderBy: This filter is used to filter or order an array by an expression.
limitTo: This filter is used to limit the string/array into a specified length or number of elements or characters.
json: This filter is used to format the object to a JSON string.
filter: this filter selects the subset of items from an array.
date: This filter is used to format the date to the specified format.
number: This filter is used to format numbers to a string.
Examples to add filters to expressionLet us how to add filters to expression with the help of examples:
Example #1: UppercaseCode:
angular.module(‘myApp’, []).controller(‘personCtrl’, function($scope) { $scope.firstName = “xyz”, $scope.lastName = “abc” });
Output :
Example #2: LowercaseCode:
angular.module(‘myApp’, []).controller(‘personCtrl’, function($scope) { $scope.firstName = “XYZ”, $scope.lastName = “ABC” });
Output :
Example #3: currency
Code:
var app = angular.module(‘myApp’, []); app.controller(‘currencyCtrl’, function($scope) { $scope.price = 60; });
Output :
Examples to add filters to directivesLet us see how to add filters to directives with the help of examples:
Example #1: orderByangular.module(‘myApp’, []).controller(‘nameandcountryCtrl’, function($scope) { $scope.names = [ {nameEmp:’anil’,countryEmp:’England’}, {nameEmp:’sumit’,countryEmp:’Sweden’}, {nameEmp:’arpita’,countryEmp:’Norway’}, {nameEmp:’pankaj’,countryEmp:’Norway’}, {nameEmp:’joe’,countryEmp:’Denmark’}, {nameEmp:’aman’,countryEmp:’Sweden’}, {nameEmp:’viman’,countryEmp:’Denmark’}, {nameEmp:’manav’,countryEmp:’England’}, {nameEmp:’Kapil’,countryEmp:’Netherland’} ]; $scope.orderByMe = function(x) { $scope.myOrderBy = x; } });
Output :
Example #2: LimtToCode:
<script src= var app = angular.module(‘myApp’, []); app.controller(‘myCtrl’, function($scope) { $scope.string = “”; });
Output:
Example #3: JsonCode:
<script src= var app = angular.module(‘result’, []); app.controller(‘resultCtrl’, function($scope) { $scope.names = { “Aman” : 356, “Vijay” : 908, “Pamkaj” : 645, “Chinmay” : 195, “Joe” : 740 }; });
Output :
Example #4: dateWhen we do not specify the date format it takes the default format as ‘MMM d, yyyy’. Here time zone parameter is optional. takes two parameter format and time zone.
Some predefined date format is as follows:
“medium time”: Equivalent to “h:mm:ss a” (2:35:05 AM)
“short date”: Equivalent to “M/d/yy” (5/7/19)
“medium”: Equivalent to “MMM d, y h:mm: ss a”
“long date”: Equivalent to “MMMM d, y” (May 7, 2023)
“short”: Equivalent to “M/d/yy h: mm a”
“short-time”: Equivalent to “h: mm a” (2:35 AM)
“full date”: Equivalent to “EEEE, MMMM d, y” (Tuesday, May 7, 2023)
“medium date”: Equivalent to “MMM d, y” (May 7, 2023)
Code:
<script src= var app = angular.module(‘gfgApp’, []); app.controller(‘dateCntrl’, function($scope) { $scope.today = new Date(); });
Output :
Example #5: numbercode:
<script src= var app = angular.module(‘gfgApp’, []); app.controller(‘numberCntrl’, function($scope) { $scope.value = 75560.569; });
Output:
Advantages of filters in AngularJsFilters are used to manipulate our data. They provide faster processing and hence enhance the performance as well. Filters are very robust as well.
ConclusionWe can use filters anywhere in our angular application like a directive, expression, controller, etc. We can also create custom filters according to which property we want to sort our data. It also reduces code and makes it more readable and optimizes and by creating custom filters we can maintain them into separate files.
Recommended ArticlesWorking Of The Push() Function In Perl With Examples
Introduction to Perl push
In Perl, the push() function is defined as a function to stack up on the elements or add elements to the existing set of items used in implementing the stack or array of elements for either adding or removing the elements using push and pop functions in Perl. In general, the push() function can be defined as an array or stack function for inserting or adding the set of items or values to another set or array of items where this push function is independent of the type of values passed in the set of elements which means the set of elements can have alphabets, numerical or both alpha-numeric values.
Start Your Free Software Development Course
Working of push() function in Perl with ExamplesIn this article, we will discuss the push() function provided by Perl for inserting or adding a set of elements to the existing stack or array of elements which is mainly used as a stack function along with the pop() function, which does the opposite of push() function which means the pop() removes or deletes the set or list of elements from the stack or array of elements. In Perl language, the push() function is defined as the insertion of items to the array or stack that is passed as an argument to this push() function, and also we need to pass another array to store these added items to the defined array and returns the array with added elements.
Now let us see the syntax and Parameters of the push() function in Perl:
Syntax:
push( arr_name, res_list)Parameters:
arr_name: This parameter is used to specify the array name that is declared at the beginning of the code, which already has elements, and the elements are added to this array.
res_list: This parameter is used to specify the set or list of elements separated by a comma that needs to be added to the array defined, which is the first argument to the push() function.
This push() function returns again a set of elements as a new array having the elements of the previous array along with the added elements to this previous or defined array.
Examples of push() function in PerlNow let us see a simple example of how to demonstrate the push() function in Perl:
Example 1 #!/usr/bin/perl print "Demonstration of push() function in Perl:"; print "n"; print "n"; @arr1 = ('Educba ', 'Google ', 'Opera '); print "The first array is given as follows: "; print "n"; foreach $x (@arr1) { print "$x"; print "n"; } print "n"; @arr2 = (20, 40, 60); print "The second array is given as follows: "; print "n"; foreach $r (@arr2) { print "$r"; print "n"; } print "n"; print "After applying push() function to the given arrays"; print "n"; push(@arr1, 'Explorer ', 'UC '); push(@arr2, (80, 100 )); print "The new array after arr1 is applied with push() is as follows:"; print "n"; foreach $y (@arr1) { print "$y"; print "n"; } print "n"; print "The new array after arr2 is applied with push() is as follows:"; print "n"; foreach $s (@arr2) { print "$s"; print "n"; }Output:
In the above program, we are declaring two different arrays one contains string type, and another contains numeric type values. In the above code, we first print all the elements in the array that is declared at the beginning, and then later, we call the push function. We pass the array such as arr1 and arr2, followed by the elements that need to be added to the previously declared array. Then we are printing the new array that has extra elements ( “Explorer” and “UC to arr1, “80” and “100” to arr2) along with the previous elements in both the arrays arr1 and arr2 now contains the elements that were pushed to the previously declared arrays using push() function such as arr1 and arr2 will now have 5 elements in them as arr1 = (‘Educba’, ‘Google’, ‘Opera’, ‘Explorer’, ‘UC’) and arr2 = (20, 40, 60, 80, 100). The output shows the new array, and the values are printed using the foreach loop.
In the above code, we should note that we have passed arguments to the push() function, but if we do not pass any arguments to the function, it will throw an error saying pass enough arguments to execute the push() function Perl. We can see in the below screenshot of the output of the above code that is modified where “push()” only called instead of any other arguments.
Example 2Code:
#!/usr/bin/perl print "Demonstration of use of push() function in Perl:"; print "n"; print "n"; @arr1 = ('Educba ', 'Google ', 'Opera '); print "The first array is given as follows: "; print "n"; foreach $x (@arr1) { print "$x"; print "n"; } print "n"; @arr2 = (20, 40, 60); print "The second array is given as follows: "; print "n"; foreach $r (@arr2) { print "$r"; print "n"; } print "n"; print "After applying push() function to the given arrays"; print "n"; push(@arr1, 'Explorer ', 'UC '); print "n"; print "After applying push() function directly"; print "n"; push @arr2, (50, 70); print "n"; print @arr2; print "n"; print "Applying push() function for joining or appending two arrays"; print "n"; push(@arr1,@arr2); print @arr1; print "n"; print "n"; print "Applying push() function for adding to array reference"; print "n"; my @arr = qw(Python Perl); my $arr_ref = @arr; push ( @{ $arr_ref }, qw(Java Ruby)); print "@{ $arr_ref }n"; exit 0;Output:
In the above program, we can see we are using the push function directly to add the elements, and we also saw how to push() can be used for joining two arrays, and we also saw how we could add elements to the array reference. The output is as shown in the above screenshot.
ConclusionIn this article, we conclude that Perl’s push() function is used to push the elements to the array elements. In this article, we saw a simple example of how the push() function is used on different types of values. In this, we also saw various use of the push() function in appending of the arrays, and we also saw how to add elements to the array reference.
Recommended ArticlesThis is a guide to Perl push. Here we discuss the Working of the push() function in Perl with Examples and how the push() function is used on different types. You may also have a look at the following articles to learn more –
Working Of Python Uuid With Examples
Introduction to Python UUID
In this article, we will discuss Python UUID which is a Python module used for implementing or generating the universally unique identifiers and is also known as GUID globally unique identifiers. Python UUID module generates the identifiers randomly which have the value of 128 bit long and these identifiers are useful for documents or information in computer systems, apps, hosts, and many different situations that will use unique identifiers. This Python UUID module provides different immutable Objects and different versions of functions such as uuid1(), uuid3(), uuid4(), uuid5() which are used for generating UUID’s of versions 1, 3, 4, and 5.
Start Your Free Software Development Course
Working of Python UUID with ExamplesIn Python, there is a library or module which is inbuilt and is used for generating unique identifiers that are universal or global and this module is known as UUID, this module can also generate different versions of UUIDs and these modules are immutable which means their value cannot be altered once generated. UUID is mainly composed of 5 components with fixed lengths and each component is separated by a hyphen and uses read attributes to define the UUID string. This Python UUID is implemented based on RFC 4211 which includes different algorithms and information regarding the unique identifiers that are to be generated along with the required versions of UUIDs. In Python, this module provides various functions for different versions such as uuid1(), uuid3(), uuid4() and uuid5().
In Python, the UUID module provides various read-only attributes such as:
UUID.bytes which includes a 16-byte string.
UUID.fields which includes fields like time, clock_seq, node, etc.
UUID.hex can hold the 32-bit hexadecimal string.
UUID.int can hold 128-bit integer
UUID.Safe this attribute tells us the uuid version used is safe or not.
Examples of Python UUIDIn the below section let us see a few examples of the use of function uuid1(), uuid3(), uuid4() and uuid5() using Python UUID module which is mainly used for generating UUID using MAC address. We will also see how the UUID looks like which means the structure of UUID.
Example #1But we should note that when using uuid1() it might display network details such as the network address of the computer in UUID so it is not so safe to use uuid1() as it may arise privacy problems because it uses the systems MAC address. Let us see a simple example.
Code:
import uuid print("Progam to demonstrate uuid1() function:") print("n") uuid_version_1 = uuid.uuid1() print("UUID of version one is as follows", uuid_version_1)Output:
In the above program, we can see the uuid1() function is used which generates the host id, the sequence number is displayed. We can compute these function values using the MAC address of the host and this can be done using the getnode() method of UUID module which will display the MAC value of a given system. Say for example
print(hex(uuid.getnode())) Example #2Code:
import uuid print("Program to demonstrate uuid4() function:") print("n") unique_id = uuid.uuid4() print ("The unique id generated using uuid4() function : ") print (unique_id)Output:
In the above program, we can see a unique id is generated using uuid4(). The uuid4() generates id using cryptographically secure random number generators hence there is less chance of collision.
Now we will see uuid3() and uuid5() where we saw a generation of UUID using random numbers now we will see how to generate UUIDs using names instead of random numbers using uuid3() and uuid5() which uses cryptographic hash values such as MD5 or SHA-1 to combine values with the names like hostnames, URLs, etc. In general, uuid3() and uuid5() versions are hashing namespace identifiers with a name, and few namespaces are defined by UUID module such as UUID.NAmESPACE_DNS, UUID.NAmESPACE_URL, etc. Now let us see an example below.
Example #3Code:
import uuid print("Program to demonstrate uuid3() and uuid5() is as follows:") print("n") for hostname in hosts_sample: print("Hostname specified is as follows: ",hostname) print('tThe SHA-1 value of the given hostname:', uuid.uuid5(uuid.NAMESPACE_DNS, hostname)) print('tThe MD5 value of the given hostname :', uuid.uuid3(uuid.NAMESPACE_DNS, hostname)) print("n")In the above program, we can see we are using uuid3() and uuid5() functions which generate UUID at different times but with the same namespace and same name. In the above program, we have two different hostnames and we are iterating using for loop. We can specify any number of hostnames and can iterate it using for loop.
As UUID is a unique universal identifier there are some privacy issues as we saw in the above section uuid1() compromises with privacy as it uses systems MAC address whereas uuid4() doesn’t compromise with privacy hence it uses a random number generator for generating UUIDs. Therefore we can say uuid1() is not safe to use and uuid4() is safer than uuid1(). Therefore to check if the UUID functions are safe in the latest Python version 3.7 an instance of UUID such as is_safe attribute is used to check for UUID is safe or not. UUIDs are used in various applications such as in web apps, database systems, etc. In Python, we can convert UUID to string and vice versa using str class and we can obtain string format removing the hyphen that is used for separation of components in UUID using string method replace() by replacing “-” with “” say for example
UUID_id = uuid.uuid1() str_uuid = str(UUID_id). replace("-", "")And similarly, we can convert the string back to UUID using UUID instance such as follows:
uuid_id = uuid.UUID(string) ConclusionIn this article, we conclude that UUID is a unique universal identifier and is also known as a global identifier. In this article, we also saw the Python UUID module to generate the identifiers using a few uuid functions of different versions and we also saw different uuid() versions such as uuid1(), uuid3(), uuid4(), and uuid5() with examples and their privacy terms. In this, we also saw different read attributes, safety checks for uuid() function, and also saw the conversion of UUID to string and vice versa.
Recommended ArticlesThis is a guide to Python UUID. Here we also discuss the introduction and working of python uuid along with different examples and its code implementation. You may also have a look at the following articles to learn more –
Update the detailed information about Learn The Implementation Of Db2 Cast With Examples on the Minhminhbmm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!