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

Sunday, December 12, 2010

LogLogic Leverages MySQL and Oracle Linux to Improve Performance and Reliability for its Critical Business Offerings

Oracle Enables LogLogic to Create Scalable Software Infrastructure for its Security Information and Event Management Solutions
Redwood Shores, Calif. – October 29, 2010
News Facts
To better support the dynamic needs of its growing business, LogLogic, Inc. has integrated the combination of MySQL and Oracle Linux into its comprehensive suite of security information and event management (SIEM) products that help its more than 1,000 large enterprise customers to achieve regulatory compliance, protect valuable customer information, and improve the efficiency of IT operations.
Speed, reliability and scalability are at the heart of LogLogic’s product value proposition. As customers’ requirements grew, LogLogic’s products needed to scale substantially to accommodate demand.
As a result, LogLogic embedded MySQL as the data processing engine for its products. The affordable, scalable, and robust solution enabled LogLogic to comfortably handle its expanding processing requirements, which include the receipt and indexing of more than a quarter of a million log entries per second and tens of billions of records per day.
The company also deployed Oracle Linux as the operating system, and uses Oracle Unbreakable Linux support, for its LogLogic 5 hardware appliance, allowing it to meet growing customer demand for testing and certification of storage and other environments.

With MySQL and Oracle Linux, LogLogic now has a reliable and scalable foundation for its product suite and can quickly provide a 360-view into customer operations, security stance, and more.
With a single point of support for both MySQL and Oracle Linux, leveraging the Oracle Unbreakable Linux support program, LogLogic is able to quickly resolve issues and more effectively meet the 24x7 requirements of its customers.
Supporting Quote
"As a medium-sized company, we benefit greatly from the processing power and economies provided by MySQL and Oracle’s rigorous testing and range of experts when it comes to Oracle Linux,” said Bill Roth, Executive Vice President, LogLogic, Inc. “Oracle readily identifies bugs and provides fixes and patches ahead of the RedHat distribution. With the combination of MySQL and Oracle Linux as the foundation, we can meet our business objectives and the certification and testing requirements of our enterprise customers with confidence.”

Monday, September 22, 2008

Meningkatkan Performa Database MySQL

Langkah berikut bisa digunakan untuk meningkatkan kecepatan akses terhadap database MySQL, terutama jika akses dilakukan dari komputer dengan sistem non Linux.
1. Memperbaiki DNS setting dan memasukkan ip address / nama host client yang mengakses mysql kedalam file /etc/hosts di server mysql.
Proses edit file /etc/hosts ini bisa dilakukan menggunakan webmin ataupun diedit langsung. Berdasarkan ujicoba langsung, tips ini meningkatkan kecepatan koneksi hingga 10X
2. Memperbaiki / meningkatkan setting konfigurasi MySQL pada file my.cnf.
Secara default, setting mysql menggunakan setting normal dengan memori kecil.

# This is for a system with little memory (32M - 64M) where MySQL plays
# an important part, or systems up to 128M where MySQL is used together with
# other programs (such as a web server)
Dengan memori yang ada pada server (misalnya sebesar 1 GB), kemampuan MySQL dapat lebih ditingkatkan dengan menaikkan key_buffer_Size (untuk model tabel MYISAM) dan innodb_buffer_pool_size (untuk tipe table Inno-db) dan table_cache. Jangan lupa, angka yang diisikan adalah angka dalam bentuk umum memory (kelipatan dari 2n), misalnya 128 MB, 256 MB, 512 MB dll.
Dalam beberapa proses instalasi, biasanya ada juga file konfigurasi untuk mysql yang dijalankan pada komputer dengan memori besar. Nama file konfigurasinya : my-large.cnf. Pelajari file konfigurasi tersebut agar bisa diujicoba pada file konfigurasi my.cnf.
Sebelum melakukan perubahan setting, backup terlebih dahulu konfigurasi yang lama, untuk berjaga-jaga jika setting yang baru justru memunculkan masalah. Berdasarkan pengalaman, setting yang tidak tepat-terlalu tinggi misalnya-membuat MySQL tidak bisa dijalankan.
Jangan lupa, perubahan konfigurasi MySQL sebaiknya dilakukan dalam posisi MySQL off sehingga setelah selesai dire-konfigurasi bisa langsung ditest.
3. Meningkatkan kapasitas memori server
Memori yang lebih tinggi akan membuat server leluasa dalam melayani trafik yang tinggi. Jika memori mencukupi, server tidak akan menggunakan memori cadangan dari swap file yang biasanya berimplikasi pada kecepatan akses data.
4. Pada aplikasi, hindari query SELECT yang tidak spesifik seperti SELECT * …
Pastikan memilih kolom yang akan diambil dan sedapat mungkin hindari model Select *
5. Gunakan indeks pada key table yang sering digunakan. Misalnya pada tabel karyawan yang menggunakan NIK (Nomor Induk Karyawan) sebagai primary key, indeks table menggunakan key ini. Jika ada proses query yang sering menggunakan nama field lainnya, buat indeks juga untuk field tersebut.
Referensi :
MySQL Amazing Tips to Improve, Tuning and Increase MySQL Performance
http://dev.mysql.com/books/hpmysql-excerpts/ch06.html
http://dev.mysql.com/doc/refman/5.0/en/server-parameters.html
http://www.linux-mag.com/index.php?option=com_content&task=view&id=911&Itemid=2035

Tuning MySQL Performance



I just stumbled across this interesting mysql tuning script called MySQLTuner. Don’t see this (or any other similar script) as the magical tool that will optimize your mysel server… There is no such thing, because there are so many different applications and each will require its specific database tunings.
Still, mysqltuner can be very useful tool in many cases, like for ex:

it gives a quick overview on your running mysql configuration and some common sense recommendations.
i really liked how it computes the total amount of memory needed for the current configuration (assuming all global buffers will be used and the maximum number of threads being connected).
very simple usage: you just have to download and run it.

wget http://mysqltuner.com/mysqltuner.pl
perl mysqltuner.pl
The output for a server that has most of the parameters on default might look like:

# ./mysqltuner.pl
MySQL High-Performance Tuner - Major Hayden
Bug reports, feature requests, and downloads at mysqltuner.com
Run with â€˜Ă˘€“help’ for additional options and output filtering
[OK] Currently running supported MySQL version 5.0.44-log
——– General Statistics ————————————————–
[–] Up for: 15s (15 q [1.000 qps], 8 conn, TX: 20K, RX: 894)
[OK] Maximum possible memory usage: 318.7M (63% of installed RAM)
[OK] Slow queries: 0%
[OK] Highest usage of available connections: 2%
[!!] Key buffer size / total MyISAM indexes: 8.0M/64.8M
[!!] Query cache is disabled
[OK] Temporary tables created on disk: 19%
[!!] Thread cache hit rate: 12%
[OK] Table cache hit rate: 80%
[OK] Open file limit used: 4%
[OK] Table locks acquired immediately: 100%
——– Recommendations —————————————————–
General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Variables to increase:
key_buffer_size (> 64.8M)
query_cache_size (>= 8M)
Variables to decrease:
long_query_time (<= 5)
max_seeks_for_key (<= 100)From its documentation:

Memory Usage: Calculates MySQL memory usage at max load and makes recommendations for increasing or decreasing the MySQL memory footprint. Per-thread and server-wide buffer data is calculated separately for an accurate snapshot of the server’s configuration.
Slow Queries: Reviews the amount of slow queries relative to the total queries. Slow query time limits are also analyzed and recommendations are made.
Connections: Current and historical connection counts are reviewed.
Key Buffer: Takes configuration data and compares it to the actual indexes found in MyISAM tables. Key cache hit rates are calculated and variable adjustments are suggested.
Query Cache: Query cache hit rates and usage percentages are used to make recommendations for the query cache configuration variables.
Sorting & Joins: Per-thread buffers that affect sorts and joins are reviewed along with the statistics from the queries run against the server.
Temporary Tables: Variable recommendations are made to reduce temporary tables that are written to the disk.
Table Cache: Compares total tables opened to the currently open tables. Calculates the table cache hit rate in order to make suggestions.
Open Files: Determines if the server will approach or run into the open file limit set by the operating system or the MySQL server itself.
Table Locks: Finds table locking that forces queries to wait and makes suggestions for reducing locks that require a wait.
Thread Cache: Calculates how many times MySQL must create a new thread to respond to a query.
Aborted Connections: Finds applications that are not closing connections to MySQL properly.
Read/Write Ratios: Calculates the percentage of read and write operations on your MySQL installation.
Check it out as it is definitely an interesting script that will give you a quick look at the configuration of your mysql server and start your journey to optimize your mysql server.

Friday, May 23, 2008

Top 84 MySQL Performance Tips

MySQL is a widely used and fast SQL database server. It is a client/server implementation that consists of a server daemon (mysqld) and many different client programs/libraries.
You can check the same tips from here.Here is very useful tips for all mysql DBA's,Developers these tips are noted from MySQL Camp 2006 suggested by mysql community experts.
Kaj (Most Excellent Obvious Facilitator) Index stuff.
Ronald Don't Index Everything Use benchmarking
Minimize traffic by fetching only what you need.
Paging/chunked data retrieval to limit
Don't use SELECT *
Be wary of lots of small quick queries if a longer query can be more efficient
Use EXPLAIN to profile the query execution plan Use Slow Query Log (always have it on!)
Don't use DISTINCT when you have or could use GROUP BY Use proper data partitions
For Cluster. Start thinking about Cluster *before* you need them Insert performance

Batch INSERT and REPLACE
Use LOAD DATA instead of INSERT
LIMIT m,n may not be as fast as it sounds
Don't use ORDER BY RAND() if you have > ~2K records
Use SQL_NO_CACHE when you are SELECTing frequently updated data or large sets of data
avoid wildcards at the start of LIKE queries
avoid correlated subqueries and in select and where clause (try to avoid in)
config params --
no calculated comparisons -- isolate indexed columns
innodb_flush_commit=0 can help slave lag
ORDER BY and LIMIT work best with equalities and covered indexes
isolate workloads don't let administrative work interfere with customer performance. (ie backups)
use optimistic locking, not pessimistic locking. try to use shared lock, not exclusive lock. share mode vs. FOR UPDATE
use row-level instead of table-level locking for OLTP workloads
Know your storage engines and what performs best for your needs, know that different ones exist.
use MERGE tables ARCHIVE tables for logs
Optimize for data types, use consistent data types. Use PROCEDURE ANALYSE() to help determine if you need less
separate text/blobs from metadata, don't put text/blobs in results if you don't need them
if you can, compress text/blobs
compress static data
don't back up static data as often
derived tables (subqueries in the FROM clause) can be useful for retrieving BLOBs w/out sorting them. (self-join can speed up a query if 1st part finds the IDs and use it to fetch the rest)
enable and increase the query and buffer caches if appropriate
ALTER TABLE...ORDER BY can take chronological data and re-order it by a different field
InnoDB ALWAYS keeps the primary key as part of each index, so do not make the primary key very large, be careful of redundant columns in an index, and this can make the query faster
Do not duplicate indexes
Utilize different storage engines on master/slave ie, if you need fulltext indexing on a table.
BLACKHOLE engine and replication is much faster than FEDERATED tables for things like logs.
Design sane query schemas. don't be afraid of table joins, often they are faster than denormalization
Don't use boolean flags
Use a clever key and ORDER BY instead of MAX
Keep the database host as clean as possible. Do you really need a windowing system on that server?
Utilize the strengths of the OS
Hire a MySQL (tm) Certified DBA
Know that there are many consulting companies out there that can help, as well as MySQL's Professional Services.
Config variables & tips:
use one of the supplied config files
key_buffer, unix cache (leave some RAM free), per-connection variables, innodb memory variables
be aware of global vs. per-connection variables
check SHOW STATUS and SHOW VARIABLES (GLOBAL|SESSION in 5.0 and up)
be aware of swapping esp. with Linux, "swappiness" (bypass OS filecache for innodb data files, innodb_flush_method=O_DIRECT if possible (this is also OS specific))
defragment tables, rebuild indexes, do table maintenance
If you use innodb_flush_txn_commit=1, use a battery-backed hardware cache write controller
more RAM is good so faster disk speed
use 64-bit architectures
Know when to split a complex query and join smaller ones
Debugging sucks, testing rocks!
Delete small amounts at a time if you can
Archive old data -- don't be a pack-rat! 2 common engines for this are ARCHIVE tables and MERGE tables
use INET_ATON and INET_NTOA for IP addresses, not char or varchar
make it a habit to REVERSE() email addresses, so you can easily search domains
--skip-name-resolve
increase myisam_sort_buffer_size to optimize large inserts (this is a per-connection variable)
look up memory tuning parameter for on-insert caching
increase temp table size in a data warehousing environment (default is 32Mb) so it doesn't write to disk (also constrained by max_heap_table_size, default 16Mb)
Normalize first, and denormalize where appropriate.
Databases are not spreadsheets, even though Access really really looks like one. Then again, Access isn't a real database
In 5.1 BOOL/BIT NOT NULL type is 1 bit, in previous versions it's 1 byte.
A NULL data type can take more room to store than NOT NULL
Choose appropriate character sets & collations -- UTF16 will store each character in 2 bytes, whether it needs it or not, latin1 is faster than UTF8.
make similar queries consistent so cache is used
Have good SQL query standards
Don't use deprecated features
Use Triggers wisely
Run in SQL_MODE=STRICT to help identify warnings
Turning OR on multiple index fields (<5.0) into UNION may speed things up (with LIMIT), after 5.0 the index_merge should pick stuff up.
/tmp dir on battery-backed write cache
consider battery-backed RAM for innodb logfiles
use min_rows and max_rows to specify approximate data size so space can be pre-allocated and reference points can be calculated.
as your data grows, indexing may change (cardinality and selectivity change). Structuring may want to change. Make your schema as modular as your code. Make your code able to scale. Plan and embrace change, and get developers to do the same.
pare down cron scripts
create a test environment
try out a few schemas and storage engines in your test environment before picking one.
Use HASH indexing for indexing across columns with similar data prefixes
Use myisam_pack_keys for int data
Don't use COUNT * on Innodb tables for every search, do it a few times and/or summary tables, or if you need it for the total # of rows, use SQL_CALC_FOUND_ROWS and SELECT FOUND_ROWS()
use --safe-updates for client
Redundant data is redundant
Use INSERT ... ON DUPLICATE KEY update (INSERT IGNORE) to avoid having to SELECT
use groupwise maximum instead of subqueries
be able to change your schema without ruining functionality of your code
source control schema and config files
for LVM innodb backups, restore to a different instance of MySQL so Innodb can roll forward
use multi_query if appropriate to reduce round-trips
partition appropriately
partition your database when you have real data
segregate tables/databases that benefit from

Monday, May 12, 2008

Solution to MySQL Replication Problems: Master DB crashed

It is commons that replication will hang after master database crashed. And the error message you will get when you show slave status is:
Client requested master to start replication from impossible position (server_errno=1236)
This happened because MySQL write to bin-log in batch basis. If every bit of your data is mission critical and any inconsistent between master and salve is not accectable, then you should redo you replication all over again.
So far I do not found any way to prevent this replication failure. However, you may add the follwing line into you my.cnf to reduce the chances it happen:
sync_binlog=1
This means that MySQL will write to bin-log after each update instead of write in batch. As you may expect, this will reduce the performance of the database.
Else, there is another way to resume the replication. The solution is illustrate in this article: Client asks master to start replication from impossible position

I get this question a lot. Why does a slave report that it's trying to replicate from an impossible position? 9 times out of 10 it's because the master crashed and when it came back online a new binlog file was made.
mySQL caches binlog events in the binlog cache, basically events are stored in memory and flushed to disk when the dirty buffer fills up. I believe the variable is called binlog_cache_size.
Here are some steps to recover from this:
Go onto the master execute
SHOW MASTER STATUS
Look at the output and find the log that the slave is pointing to. Look at the File size field.
Next look at the slave output from the slave reporting the issue. Look at Exec_Master_Log_Pos, is that value greater then the File Size on the master if so issue
CHANGE MASTER TO MASTER_LOG_FILE=[NEXT FILE], MASTER_LOG_POS=4;
slave start;
Now if your super sensitive of lost events because a row or two could of been lost from this replication event, do some spot testing for tables written to often. Look for anything that has changed within the outage window, if the data doesn't match the slave then you're master and slave are out of sync, and will require a full clone to get the data back in sync.

Tuesday, March 4, 2008

How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual Basic .NET

Description of the Technique
The SqlDataAdapter object serves as a bridge between an ADO.NET DataSet object and a SQL Server database. SqlDataAdapter is an intermediary object that populates an ADO.NET DataSet object with data that is retrieved from a SQL Server database and then updates the database to reflect the changes (such as inserts, updates, and deletes) that are made to the data by using the DataSet object.The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object.

These properties are SqlCommand objects that specify the INSERT, the UPDATE, and the DELETE Transact-SQL commands that are used to post the dataset modifications to the target database. The SqlCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the SqlCommandBuilder object.The first code sample in this article demonstrates how to use the SqlCommandBuilder object to automatically generate the UpdateCommand property of the SqlDataAdapter object. The second sample uses a scenario in which you cannot use automatic command generation. The second sample demonstrates how to manually create and use a SqlCommand object as the UpdateCommand property of a SqlDataAdapter object.
Create the Sample SQL Server Table
To create a sample SQL Server table that you can use in the Visual Basic .NET code samples that are documented in this article, follow these steps:
1.Open SQL Query Analyzer, and then connect to the database in which you want to create the sample table. The code samples in this article use the Northwind database that is included with SQL Server.
2.To create a sample table that is named CustTest and to insert a record into the table, run the following Transact-SQL statements:Create Table CustTest
(
CustID int primary key,
CustName varchar(20)
)
Insert into CustTest values(1,'John')

Code Sample 1: Automatically Generated Commands
If the SELECT statement that you use to retrieve the data that populates a DataSet is based on a single database table, you can use the CommandBuilder object to automatically generate the DeleteCommand, the InsertCommand, and the UpdateCommand properties of the DataAdapter. This simplifies and reduces the code that is required to perform INSERT, UDPATE, and DELETE operations.As a minimum requirement, you must set the SelectCommand property to generate commands automatically. The table schema that the SelectCommand retrieves determines the syntax of the INSERT, the UPDATE, and the DELETE statements that are automatically generated.The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated.To create a sample Visual Basic .NET console application that demonstrates how to use the SqlCommandBuilder object to automatically generate the DeleteCommand, the InsertCommand, and the UpdateCommand properties of the SqlCommand object for a SqlDataAdapter object, follow these steps:
1.To create a new Visual Basic .NET console application, follow these steps:
a.Start Microsoft Visual Studio .NET.
b.On the File menu, point to New, and then click Project.
c.Click Visual Basic Projects under Project Types, and then click Console Application under Templates.
2.Replace the default contents of Module1 with the following code:Imports System.Data.SqlClient
Imports Console = System.Console
Module Module1
Sub Main()
Dim cn As New SqlConnection()
Dim CustomersDataSet As New DataSet()
Dim da As SqlDataAdapter
Dim dr As DataRow
Dim cmdBuilder As SqlCommandBuilder

'Set the connection string of the SqlConnection object to connect to the
'SQL Server database in which you created the sample table.
cn.ConnectionString = "Server=.;Database=northwind;UID=sa;PWD=;"
cn.Open()

'Initialize the SqlDataAdapter object by specifying a Select command
'that retrieves data from the sample table.
da = New SqlDataAdapter("select * from CustTest order by CustId", cn)
'Initialize the SqlCommandBuilder object to automatically generate and initialize
'the UpdateCommand, InsertCommand and DeleteCommand properties of the SqlDataAdapter.
cmdBuilder = New SqlCommandBuilder(da)
'Populate the dataset by running the Fill method of the SqlDataAdapter.
da.Fill(CustomersDataSet, "Customers")

'Display the Update, Insert and Delete commands that were automatically generated
'by the SqlCommandBuilder object.
Console.WriteLine("Update command Generated by the Command Builder : ")
Console.WriteLine("==================================================")
Console.WriteLine(cmdBuilder.GetUpdateCommand.CommandText)
Console.WriteLine(" ")
Console.WriteLine("Insert command Generated by the Command Builder : ")
Console.WriteLine("==================================================")
Console.WriteLine(cmdBuilder.GetInsertCommand.CommandText)
Console.WriteLine(" ")
Console.WriteLine("Delete command Generated by the Command Builder : ")
Console.WriteLine("==================================================")
Console.WriteLine(cmdBuilder.GetDeleteCommand.CommandText)
Console.WriteLine(" ")
'Write out the value in the CustName field before updating the data using the DataSet.
Console.WriteLine("Customer Name before Update : " & CustomersDataSet.Tables("Customers").Rows(0)("CustName"))
'Modify the value of the CustName field.
CustomersDataSet.Tables("Customers").Rows(0)("CustName") = "Jack"
'Post the data modification to the database.
da.Update(CustomersDataSet, "Customers")
Console.WriteLine("Customer Name updated successfully")
'Close the database connection.
cn.Close()
Console.ReadLine()
End Sub
End Module
3.Save and then run the application. A console window opens and displays the following output:
Update command Generated by the Command Builder :
==================================================
UPDATE CustTest SET CustID = @p1 , CustName = @p2 WHERE ( CustID = @p3 AND CustName = @p4 )

Insert command Generated by the Command Builder :
==================================================
INSERT INTO CustTest( CustID , CustName ) VALUES ( @p1 , @p2 )

Delete command Generated by the Command Builder :
==================================================
DELETE FROM CustTest WHERE ( CustID = @p1 AND CustName = @p2 )

Customer Name before Update : John
Customer Name updated successfully

4.Press any key to dismiss the console window and to stop the application.
Sample 2: Manually Create and Initialize the UpdateCommand Property
The output that Code Sample 1 generates indicates that the logic to generate commands automatically for UPDATE statements is based on optimistic concurrency. That is, records are not locked for editing, and other users or processes can modify records whenever.Because a record can be modified after it is returned from the SELECT statement but before the UPDATE statement is issued, the UPDATE statement that is automatically generated contains a WHERE clause so that a row is updated only if it contains all of the original values. This is to avoid overwriting new data. If an UPDATE statement that is automatically generated tries to update a row that has been deleted or does not contain the original values that are found in the DataSet, the command does not affect any records, and a DBConcurrencyException exception is generated. To test this with the code in Code Sample 1, run the code in the Visual Studio Debugger, set a breakpoint after the DataSet has been filled but before the database is updated, and then delete the one row in the table from SQL Query Analyzer. The Update call then throws the exception.If you want the UPDATE statement to complete regardless of original values, you must explicitly set the UpdateCommand for the DataAdapter and not rely on automatic command generation. To manually create and initialize the UpdateCommand property of the SqlDataAdapter object that is used in Code Sample 1, follow these steps:
1.Replace the existing code in Sub Main of Module1 in the Visual Basic .NET console application that you created in the Code Sample 1: Automatically Generated Commands section with the following code:Dim cn As New SqlConnection()
Dim CustomersDataSet As New DataSet()
Dim da As SqlDataAdapter
Dim dr As DataRow
Dim DAUpdateCmd As SqlCommand
cn.ConnectionString = "Server=.;Database=northwind;UID=sa;PWD=;"
cn.Open()
da = New SqlDataAdapter("select * from CustTest order by CustId", cn)
'Initialize the SqlCommand object that will be used as the DataAdapter's UpdateCommand.
'Note that the WHERE clause uses only the CustId field to locate the record that is to be updated.
DAUpdateCmd = New SqlCommand("Update CustTest set CustName = @pCustName where CustId = @pCustId", da.SelectCommand.Connection)
'Create and append the parameters for the Update command.
DAUpdateCmd.Parameters.Add(New SqlParameter("@pCustName", SqlDbType.VarChar))
DAUpdateCmd.Parameters("@pCustName").SourceVersion = DataRowVersion.Current
DAUpdateCmd.Parameters("@pCustName").SourceColumn = "CustName"
DAUpdateCmd.Parameters.Add(New SqlParameter("@pCustId", SqlDbType.Int))
DAUpdateCmd.Parameters("@pCustId").SourceVersion = DataRowVersion.Original
DAUpdateCmd.Parameters("@pCustId").SourceColumn = "CustId"
'Assign the SqlCommand to the UpdateCommand property of the SqlDataAdapter.
da.UpdateCommand = DAUpdateCmd
da.Fill(CustomersDataSet, "Customers")
Console.WriteLine("Customer Name before Update : " & CustomersDataSet.Tables("Customers").Rows(0)("CustName"))
CustomersDataSet.Tables("Customers").Rows(0)("CustName") = "Jack"
da.Update(CustomersDataSet, "Customers")
Console.WriteLine("Customer Name updated successfully")
cn.Close()
Console.ReadLine()

Friday, February 8, 2008

Using the Python Interpreter

Invoking the Interpreter
The Python interpreter is usually installed as /usr/local/bin/python on those machines where it is available; putting /usr/local/bin in your Unix shell's search path makes it possible to start it by typing the command

python
to the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
On Windows machines, the Python installation is usually placed in C:\Python24, though you can change this when you're running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box:
set path=%path%;C:\python24
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn't work, you can exit the interpreter by typing the following commands: "import sys; sys.exit()".
The interpreter's line-editing features usually aren't very sophisticated. On Unix, whoever installed the interpreter may have enabled support for the GNU readline library, which adds more elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix A for an introduction to the keys. If nothing appears to happen, or if P is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
A second way of starting the interpreter is "python -c command [arg] ...", which executes the statement(s) in command, analogous to the shell's -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is best to quote command in its entirety with double quotes.
Some Python modules are also useful as scripts. These can be invoked using "python -m module [arg] ...", which executes the source file for module as if you had spelled out its full name on the command line.
Note that there is a difference between "python file" and "python When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script. (This does not work if the script is read from standard input, for the same reason as explained in the previous paragraph.)
Argument Passing
When known to the interpreter, the script name and additional arguments thereafter are passed to the script in the variable sys.argv, which is a list of strings. Its length is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter's option processing but left in sys.argv for the command or module to handle.
Interactive Mode
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (">>> "); for continuation lines it prompts with the secondary prompt, by default three dots ("... "). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!
The Interpreter and Its Environment
Error Handling
When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output.
Typing the interrupt character (usually Control-C or DEL) to the primary or secondary prompt cancels the input and returns to the primary prompt.2.1Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement.
Executable Python Scripts
On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
#! /usr/bin/env python
(assuming that the interpreter is on the user's PATH) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python.
The script can be given an executable mode, or permission, using the chmod command:
$ chmod +x myscript.py
Source Code Encoding
It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right after the #! line to define the source file encoding:
# -*- coding: encoding -*-
With that declaration, all characters in the source file will be treated as having the encoding encoding, and it will be possible to directly write Unicode string literals in the selected encoding. The list of possible encodings can be found in the Python Library Reference, in the section on codecs.
For example, to write Unicode literals including the Euro currency symbol, the ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value 164. This script will print the value 8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit:
# -*- coding: iso-8859-15 -*-
currency = u"€"
print ord(currency)
If your editor supports saving files as UTF-8 with a UTF-8 byte order mark (aka BOM), you can use that instead of an encoding declaration. IDLE supports this capability if Options/General/Default Source Encoding/UTF-8 is set. Notice that this signature is not understood in older Python releases (2.2 and earlier), and also not understood by the operating system for script files with #! lines (only used on Unix systems).
By using UTF-8 (either through the signature or an encoding declaration), characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCII characters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
The Interactive Startup File
When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.
This file is only read in interactive sessions, not when Python reads commands from a script, and not when /dev/tty is given as the explicit source of commands (which otherwise behaves like an interactive session). It is executed in the same namespace where interactive commands are executed, so that objects that it defines or imports can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 in this file.
If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like "if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')". If you want to use the startup file in a script, you must do this explicitly in the script:
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)

Monday, February 4, 2008

MYSQL PART II Update Statement

UPDATE Statement :
The UPDATE query is used to change or modify the existing values in a table.
The Update Syntax is
UPDATE tbl_name SET
col_name1=expr1 [, col_name2=expr2 ...]
[WHERE where_condition];

The UPDATE query updates the columns of existing rows in a table with the new values. The SET clause is used to indicate which columns to be modified. The WHERE clause is used to specify the conditions that identify which rows to be updated.
The following example will set the address of the student to a new address.
mysql> update student set address='welling street' where
address='victoria street';
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
But this will set all the address of the students who ever lives in victoria street will be changed to welling street.
Suppose if we want to set the address of a single student to a new address then we can choose the below option.
mysql> update student set address='welling street' where name='jack';
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
If we want to change a students mark we can use the below statement.
mysql> update student set marks=100 where name='david';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
This can also be rewritten as the following.
mysql> update student set marks=marks+2 where name='david';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
In UPDATE statement we can also use the arithmetic operations
Operator Precedence:
Operators are used to operate with two operands. Wide collection of Operators are available in MySQL. The operator precedences are shown below in the table.
Highest Precedence :=
1 , OR, XOR
2 &&, AND
3 BETWEEN, CASE, WHEN, THEN, ELSE
4 =, <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
5
6 &
7 <<, >>
8 -, +
9 *, /, DIV, %, MOD
10 ^
11 - (unary minus), ~ (unary bit inversion)
12 !, NOT
Lowest BINARY, COLLATE
If a statement contains paranthesis, then the operations inside the paranthesis are performed first. These operators will be explained in the following sections.
Type Conversion :
Type conversion takes place when operators are used with different types of operands in an expression. Some conversions are done implicitly and some need explicit conversions.
In MySQL the numbers are converted to strings and sometimes strings to numbers depending upon the condition.
Let us consider an example for converting a string to an integer.
mysql> Select 1+'11';
--> 12
Here the string '11' is converted to a number and the result of the expression is also a number.
Lets see another example for converting an integer to a string.
mysql> select concat(1, ' HIOX');
--> '1 HIOX'
We can convert or casting a number to a string explicitly. Here we use CAST() or CONCAT() function.
mysql> select 12, cast(12 as char);
--> 12, '12'
mysql> select 12, concat(12);
--> 12, '12'
Logical Operator :
MySQL supports the following logical operations :
AND(&&) Operator
OR() Operator
NOT(!) Operator
AND(&&) Operator :
The logical AND(&&) operator indicates whether the both operands are true. Lets see a statement using AND operator.
mysql> select studid, name from student where marks > 80
and marks <> select studid, name from student where marks > 80
&& marks <> select name, marks, address from student where
name like 'a%' or name like 's%';(or)
mysql> select name, marks, address from student where
name like 'a%' name like 's%';
+-------+-------+------------------+
name marks address
+-------+-------+------------------+
steve 100 5th cross street
anne 100 downing street
steve 75 downing street
anne 80 edinburgh
+-------+-------+------------------+
4 rows in set (0.00 sec)
In the above statement it will list the name, marks and address of the student whose name starts with the letter A and S.
NOT(!) Operator :
The logical NOT(!) operator have only one operand and it returns the inverse of the value.
mysql> select * from student where not (studid=1);(or)
mysql> select * from student where ! (studid=1);
+--------+-------+-------+-----------------+---------+
studid name marks address phone
+--------+-------+-------+-----------------+---------+
2 david 100 welling street 547896
4 jack 82 welling street 2436821
5 anne 100 downing street 2634821
6 steve 75 downing street 2874698
7 anne 80 edinburgh 2569843
8 mille 98 victoria street 1236547
+--------+-------+-------+-----------------+---------+
6 rows in set (0.00 sec)
It will list all the student details except the studid 1.
Comparison Operator :
Comparison operator is used to compare expressions or values. The result of the comparison will be either True(1) or False(0). MySQL supports the following comparison operators :
EQUAL(=)
LESS THAN(<) LESS THAN OR EQUAL(<=) GREATER THAN(>)
GREATER THAN OR EQUAL(>=)
NOT EQUAL(<>,!=)
BETWEEN
GREATEST
= :
Equal.
mysql> select 1 = 0;
--> 0
mysql> select 0.0 = 0;
--> 1
< : Less than. mysql> select 4.5 <> 1
mysql> select 1.1 <> 0
<= : Less than or equal. mysql> select 2.2 <= 2.2; --> 1
mysql> select 2.2 <= 2.1; --> 0
> :
Greater than.
mysql> select 7 > 2;
--> 1
mysql> select 4 > 4.1;
--> 0
>= :
Greater than or equal.
mysql> select 10 >= 10;
--> 1
mysql> select 4.4 >= 4.5;
--> 0
<>, != :
Not equal.
mysql> select 8 <> 8;
--> 0
mysql> select 7 != 7.7;
--> 1
expr BETWEEN min AND max :
If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0.
mysql> select 5 between 5 and 6;
--> 1
mysql> select 'N' between 'M' and 'O';
--> 1
This is same for the expr NOT BETWEEN min AND max, but Not.
GREATEST(value1,value2,...) :
This operator returns the largest argument, compared with two or more arguments.
mysql> select greatest('N', 'M', 'O');
--> O
mysql> select greatest(1, 2);
--> 2
The same rule is applied in finding the LEAST().
Numeric Functions :
Numeric function consists of two main sections. They are :
Arithmetic Operations
Mathematical Functions
Now, lets first discuss about Arithmetic operations.
Arithmetic Operations :
In MySQL, we have the usual Arithmetic operations. Lets see the arithmetic operators one by one with an example.
Addition (+) :
mysql> select 5+5;
--> 10
Subtraction (-) :
mysql> select 25-18;
--> 7
Multiplication (*) :
mysql> select 4*4;
--> 16
Division (/) :
mysql> select 5/3;
--> 1.67
Next lets move to the Mathematical functions
Mathematical Functions :
ABS ACOS ASIN ATAN CEIL
COS COT DEGREES EXP FLOOR
FORMAT
LN LOG LOG(B,X) LOG2
LOG10 MOD PI POWER RADIANS
RAND ROUND SIGN SIN SQRT
TAN TRUNCATE
Now lets see some Mathematical functions with an example.
ABS(X) :
This function returns the Absolute value of the given value.
mysql> select abs(5);
--> 5
mysql> select abs(-25);
--> 25
ACOS(X) :
Returns the arc Cosine value of the given number.
mysql> select acos(0);
--> 1.5707963267949
mysql> select acos(1);
--> 0
ASIN(X) :
Returns the arc Sine value of the given number.
mysql> select asin(1);
--> 1.5707963267949
mysql> select asin(0);
--> 0
ATAN(X) :
Returns the arc Tangent value of the given number.
mysql> select atan(1);
--> 0.78539816339745
mysql> select atan(2);
--> 1.1071487177941
CEIL(X) or CEILING(X) :
Returns the smallest integer nearest to the given value but not less than that.
mysql> select ceil(1.14);
--> 2
mysql> select ceiling(-1.14);
--> -1
COS(X) :
Returns the Cosine of X, where X is given in radians.
mysql> select cos(pi());
--> -1
mysql> select cos(0);
--> 1
COT(X) :
Returns the cotangent value of X.
mysql> select cot(1);
--> 0.64209261593433
mysql> select cot(45);
--> 0.61736962378356
Mathematical Functions :
Now lets see some Mathematical functions with an example.
DEGREES(X) :
This function returns the argument X, converted from radians to degrees.
mysql> select degrees(pi());
--> 180
mysql> select degrees(0.78539816339745);
--> 45
EXP(X) :
Returns the value of the base of natural logarithms(e) raised to the power of X.
mysql> select exp(-1);
--> 0.36787944117144
mysql> select exp(1);
--> 2.718281828459
FLOOR(X) :
Returns the largest integer value not greater than X.
mysql> select floor(5.68);
--> 5
mysql> select floor(-1.26);
--> 2
FORMAT(X,D) :
Formats the given number in a ##,###.## format,rounded to D decimal places.
mysql> select format(7895423.23478,2);
--> 7,895,423.23
mysql> select format(1287654.458,0);
--> 1,287,654
LN(X) :
Returns the natural logarithm of X, the base-e logarithm of X.
mysql> select ln(3);
--> 1.0986122886681
mysql> select ln(-1);
--> NULL
LOG(X) :
This function returns the natural logarithm of X, if it contains a single parameter.
mysql> select log(1);
--> 0
mysql> select log(-2);
--> NULL
LOG(B,X) :
If it contains two parameters, then returns the natural logarithm of X for an arbitrary base B .
mysql> select log(3,4512);
--> 7.659204143237
mysql> select log(1,250);
--> NULL
Mathematical Functions :
Now lets see some Mathematical functions with an example.
LOG2(X) :
Returns the base-2 logarithm of X.
mysql> select log2(7215);
--> 12.816783679379
mysql> select log2(-10);
--> NULL
LOG10(X) :
Returns the base-10 logarithm of X.
mysql> select log10(5);
--> 0.69897000433602
mysql> select log10(-5);
--> NULL
MOD(N,M), N % M, N MOD M :
This function returns the remainder of N divided by M.
mysql> select mod(123, 10);
--> 3
mysql> select 111 % 8;
--> 7
mysql> select 45 mod 4;
--> 1
PI() :
Returns the value of ?(pi).
mysql> select pi();
--> 3.141593
POW(X,Y), POWER(X,Y) :
This function returns the value of XY.
mysql> select pow(3,4);
--> 81
mysql> select pow(3,-4);
--> 0.012345679012346
RADIANS(X) :
This function returns the argument X, converted from degrees to radians.
mysql> select radians(30);
--> 0.5235987755983
mysql> select radians(45);
--> 0.78539816339745
RAND(X) :
This function returns the random floating point number between 0 & 1. If a number is given within this function ,it produces repeatable sequence of values.
mysql> select rand();
--> 0.13388662052703
mysql> select rand(10);
--> 0.65705152196535
mysql> select rand(10);
--> 0.65705152196535
mysql> select rand();
--> 0.82382530888899
mysql> select rand();
--> 0.7174667135975
mysql> select rand(10);
--> 0.65705152196535
Mathematical Functions :
Now lets see some Math functions with an example.
ROUND(X), ROUND(X,D) :
Returns the argument X, rounded to the nearest integer. If it contains two arguments, then returns X rounded to D decimal places.
mysql> select round(12.589);
--> 13
mysql> select round(-12.23);
--> -12
mysql> select round(5.258, 1);
--> 5.3
mysql> select round(5.258, -1);
--> 10
SIGN(X) :
Returns the sign of the given number as -1 if negative,0 if zero, or 1 if positive.
mysql> select sign(-89);
--> -1
mysql> select sign(0);
--> 0
mysql> select sign(123);
--> 1
SIN(X) :
Returns the sine value of X,X given in radians.
mysql> select sin(45);
--> 0.85090352453412
mysql> select sin(pi());
--> 1.2246063538224e-016
SQRT(X) :
Returns the square root of the number,the number should be a positive number.
mysql> select sqrt(144);
--> 12
mysql> select sqrt(741);
--> 27.221315177632
TAN(X) :
Returns the tangent of X, where X is given in radians.
mysql> select tan(45);
--> 1.6197751905439
mysql> select sqrt(90);
--> -1.9952004122082
TRUNCATE(X,D) :
The number is truncated to D digits after decimal point. If D is negative, the D digits before the decimal point are converted to 0.
mysql> select truncate(4.556,1);
--> 4.5
mysql> select truncate(444.556,-1);
--> 440
String Function :
Functions are predefined set of instructions that returns a value. Functions which involves strings are called as String functions. There are different types of functions availble in MySQL.
The important string functions are,
CHAR_LENGTH
CONCAT CONCAT_WS FORMAT
LCASE
LENGTH LOCATE REPEAT
REPLACE REVERSE SUBSTRING
CHAR_LENGTH(str) or CHARACTER_LENGTH(str) :
This string function returns the length of the string.
mysql> select char_length("hioxindia");
--> 9
mysql> select character_length("easycalculation");
--> 15
CONCAT(str1,str2,...) :
Returns the concatenated string of the given arguments.
mysql> select concat('hiox','india');
--> 'hioxindia'
CONCAT_WS() :
It stands for Concatenate With Separator and is a special form of CONCAT function. Returns the concatenated string of the given arguments seperated by given seperator.
mysql> SELECT CONCAT_WS('!','One','Two','Three');
--> 'One!Two!Three'
( Here '!' is the seperator)
FORMAT() :
Formats the given no and rounds to the given digits after decimal point.
mysql> SELECT FORMAT(12332.123456, 4);
--> '12,332.1235'
LCASE(str) or LOWER() :
Returns the lowercase of the given string.
mysql> select lcase('HIOX');
--> 'hiox'
mysql> select lower('EASYCALCULATION');
--> easycalculation
Like wise UPPER or UCASE returns the uppercase of the given string.
LENGTH(str) :
Returns the length of the given string in bytes. If there is a 2 byte character the length is calculated as 2. Whereas the CHAR_LENGTH calculates only the character length.
mysql> select length('HIOXINDIA');
--> 9
LOCATE(substr,str) or POSITION(substr IN Str) :
Returns the position of the first occurance of the substring in the string.
mysql> select locate('ind','hioxindia');
--> 5
mysql> select position('cul' in 'easycalculation');
--> 8
REPEAT(str,count) :
The given string is repeated for the given count.
mysql> select repeat('HIOX',2);
--> 'HIOXHIOX'
REPLACE(str,from_str,to_str) :
In the given string 'str' the 'from_str' is replaced by the 'to_str' string.
mysql> select replace('MyMYSql','My','you');
--> youMYSql
The given 'from_str' is case sensitive. Here in the above example the first 'My' is changed but not the second('MY').
REVERSE(str) :
The given string is reversed and returned.
mysql> select reverse('HIOX');
--> 'XOIH'
SUBSTRING(str,pos) :
The function returns a substring from the string 'str' starting at position 'pos'.
mysql> select substring('EASYCALCULATION', 5);
--> 'CALCULATION'
Date and Time Functions :
This function is used to manipulate the display format of a date and time. Lets see some basic functions for date and time.
CURDATE CURTIME DATEDIFF DATE_ADD
DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR
HOUR MINUTE MONTH MONTHNAME
NOW CURDATE() :
This date function returns the current date in the format 'YYYY-MM-DD' or 'YYYYMMDD'.
mysql> select curdate();
--> 2007-01-03
CURTIME() :
Returns the current time in the format 'HH:MM:SS' or 'HHMMSS'.
mysql> select curtime();
--> 17:33:07
DATEDIFF(expression1,expression2) :
expression1 and expression2 are date or date-and-time expressions. This function returns expression1 – expression2 expressed as a value in days from one date to the other. Here only the date parts will be considered for calculation.
mysql> select datediff('2007-2-6 17:33:25','2007-1-1');
--> 36
DATE_ADD(datetime, INTERVAL expression datetimetype) :
This date function adds the expression to the datetime supplied.
mysql> select date_add('2007-1-14', interval 15 day);
--> 2007-01-29
This function is same for DATE_SUB, but subtracting will take place instead of adding.
DAYNAME(date) :
Returns the name of the day for the specified date.
mysql> select dayname('2007-01-04');
--> Thursday
DAYOFMONTH(date) or DAY(date) :
Returns the date for the day of the month in the range of 1 to 31. DAY() is a synonym for DAYOFMONTH().
mysql> select dayofmonth('2007-01-04');
--> 4
DAYOFWEEK(date) :
Returns the day of the week in the numeric format as 1 for Sunday to 7 for Saturday.
mysql> select dayofweek('2007-01-04');
--> 5
DAYOFYEAR(date) :
Returns the day of the year for given date in the numeric format, in the range 1 to 366.
mysql> select dayofyear('2007-07-09');
--> 190
HOUR(time) :
Returns the hour of the specified time in the numeric format from 0 to 23.
mysql> select hour('14:46:12');
--> 14
MINUTE(time) :
Returns the minute of the specified time in the numeric format from 0 to 59.
mysql> select minute('14:46:12');
--> 46
MONTH(date) :
Returns the month for the given date in the numeric format, in the range 0 to 12. mysql> select month('2007-07-09');
--> 7
MONTHNAME(date) :
Returns the name of the month for the specified date.
mysql> select monthname('2007-07-09');
--> July
NOW() :
This date time function returns the current date and time in the format 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.
mysql> select now();
--> 2007-01-04 14:56:15

Sunday, February 3, 2008

MYSQL PART II TABLES

Creating tables :
Once you have selected the database, we can start creating tables. The CREATE statement is used to create a table in MySQL with constraint. A Constraint is restriction to the behavior of a variable.
The Create syntax is

CREATE TABLE tableName
( fieldName1 dataType(size) [NULL NOT NULL]
fieldName2 dataType(size) [NULL NOT NULL] );
If NULL is specified, the field is allowed to be left empty. If NOT NULL is specified, the field must be given a value. In the absence of either a NULL or NOT NULL, NULL is assumed.
The below example query will help you in creating table:
CREATE TABLE student
( studID INT(5),
name VARCHAR(30),
);
The above query will create the table student with fields ID and Name.
PRIMARY KEY :
A PRIMARY KEY is a field in a table that uniquely identifies a record. This attribute is used to define the field name to create a primary key.
Example :
fieldName INT UNSIGNED AUTO_INCREMENT PRIMARY KEY
The PRIMARY KEY is specified after defining the fields in the below example:
CREATE TABLE student
( studID INT UNSIGNED AUTO_INCREMENT,
name VARCHAR(30),
PRIMARY KEY(studID)
);
We can also create a compound primary key. A compound primary key is where more than one field is used to uniquely identify a record.
Lets create a table for holding student details in a class.
mysql> create table student(studid int(10), name varchar(20), address varchar(40), phone int(10));
Query OK, 0 rows affected (0.05 sec)
Desc table :
We can examine the structure of a table using the DESCRIPTION or DESC statement. The following query describes the structure of the student table.
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+---------+-------------+------+-----+---------+-------+
studid int(10) YES NULL
name varchar(20) YES NULL
address varchar(40) YES NULL
phone int(10) YES NULL
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
We can also use the SHOW FIELDS FROM statement to display the same structure.
mysql> SHOW FIELDS FROM student;
Listing Tables :
We can list all the tables in the database using SHOW TABLES query. The following query will list the tables in the current database.
mysql> show tables;
+--------------------+
Tables_in_sample
+--------------------+
student
+--------------------+
1 row in set (0.00 sec)
Deleting tables :
The DROP statement is used to delete one or more tables completely from a database.
The syntax is
DROP TABLE tbl_name
The following example deletes the student table.
mysql> drop table student;
Query OK, 0 rows affected (0.00 sec)
This query will permanently remove or delete the table student.
DROP TABLE query drops all fields in the table and deletes the table. Once the DROP TABLE statement is used, we cannot use that table. So, we should be careful with this statement.
Renaming tables :
The RENAME statement is used to rename one or more tables in a database.
The syntax is
RENAME TABLE tbl_name TO new_tbl_name
[, tbl_name2 TO new_tbl_name2] ...
The following example query renames the student table as class table.
mysql> rename table student to class;
Query OK, 0 rows affected (0.00 sec)
Now we can view the table whether the name is changed by the following query.
mysql> show tables;
+--------------------+
Tables_in_sample
+--------------------+
class
+--------------------+
1 row in set (0.00 sec)
If the query renames more than one table, renaming operations are done from left to right.
We can also swap two table names. Let us assume tmp table which does not exists.
Example :
RENAME TABLE emp1 TO tmp,
emp2 TO emp1,
tmp TO emp2;
We can also use RENAME TABLE to move a table from one database to another.
Example :
RENAME TABLE current_db.tbl_name TO other_db.tbl_name;
ALTER TABLE :
ALTER TABLE is used to change the structure of an existing table. We can add or delete columns, change the type of existing columns, or rename columns or the table itself. We can also change the comment for the table and type of the table.
The Syntax is
ALTER TABLE tbl_name alter_specification [, alter_specification] ...
The below table will describe the alter specification :
Alter Specification Description
Rename Rename a Table name
Add Add a new column, key, index
Add First Add a column First
Add After Add a column After
Drop Drop a column, Index, key
Change Change a column name
Change Type Change a column type
Modify Modify a column type
Renaming a Table :
We can also RENAME the table using ALTER TABLE. The following example query renames the table student to class.
mysql> ALTER TABLE student RENAME class;
The above query will change the table name.
Adding a column to a table :
The ADD COLUMN modifier is used to add a column to a table. The following example query adds a field called marks to the student table.
mysql> ALTER TABLE student ADD COLUMN marks INT(10);
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+---------+-------------+------+-----+---------+-------+
studid int(10) YES NULL
name varchar(20) YES NULL
address varchar(40) YES NULL
phone int(10) YES NULL
marks int(10) YES NULL
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Next we move to the alterations in displaying the tables.
Add a column First :
We can position the field using FIRST and AFTER modifiers. The following example query will place the new field as the first field in the table.
mysql> ALTER TABLE student ADD COLUMN marks INT(10) FIRST;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+---------+-------------+------+-----+---------+-------+
marks int(10) YES NULL
studid int(10) YES NULL
name varchar(20) YES NULL
address varchar(40) YES NULL
phone int(10) YES NULL
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Add a column After :
We can also place the new field next to any of the field. The following example query will place the new field immediately after the field name.
mysql> ALTER TABLE student ADD COLUMN marks INT(10) AFTER names;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+---------+-------------+------+-----+---------+-------+
studid int(10) YES NULL
name varchar(20) YES NULL
marks int(10) YES NULL
address varchar(40) YES NULL
phone int(10) YES NULL
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Next we can see how to delete and change a field.
Delete a column :
The DROP COLUMN is used to delete a column from the table.
The syntax is
ALTER TABLE tbl_name DROP col_name;
The following query drops the field marks.
mysql> ALTER TABLE student DROP COLUMN marks;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+---------+-------------+------+-----+---------+-------+
studid int(10) YES NULL
name varchar(20) YES NULL
address varchar(40) YES NULL
phone int(10) YES NULL
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
Change a column name :
When we modify a column, we have to specify the attribute of the column again. The following example renames the name field to stud_name in the student table.
mysql> ALTER TABLE student CHANGE name stud_name VARCHAR(20);
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+-----------+-------------+------+-----+---------+-------+
Field Type Null Key Default Extra
+-----------+-------------+------+-----+---------+-------+
studid int(10) YES NULL
stud_name varchar(20) YES NULL
Counting Rows :
COUNT(*) counts the number of rows in a table.
The syntax is
SELECT COUNT(*) from tbl_name;
Example :
mysql> select count(*) from student;
+----------+
count(*)
+----------+
5
+----------+
1 row in set (0.00 sec)
The above query will list the number of rows in the student table.
After inserting datas into the table, we probably want to check the datas are stored correctly. To do so, we use the SELECT statement.
The Select syntax is
SELECT what_to_select from tbl_name;
To view all the data from the table, we use the below query.
mysql> select * from student;
+--------+---------+-------+------------------+---------+
studid name marks address phone
+--------+---------+-------+------------------+---------+
1 steve 100 5th cross street 2456987
2 david 98 welling street 547896
3 michael 75 edinburgh 2598234
4 jack 82 victoria street 2436821
5 anne 100 downing street 2634821
6 steve 75 downing street 2874698
7 anne 80 edinburgh 2569843
8 mille 98 victoria street 1236547
+--------+---------+-------+------------------+---------+
8 rows in set (0.00 sec)
The above example query will list the complete details of the student table. Here * will select all the columns from the table.
LIMIT :
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. It takes one or two numeric arguments, which must both be non-negative integer constants.
Lets see an example query for SELECT LIMIT statement.
mysql> select * from student limit 2,5;
+--------+---------+-------+-----------------+---------+
studid name marks address phone
+--------+---------+-------+-----------------+---------+
3 michael 75 edinburgh 2598234
4 jack 82 victoria street 2436821
5 anne 100 downing street 2634821
6 steve 75 downing street 2874698
7 anne 80 edinburgh 2569843
+--------+---------+-------+-----------------+---------+
5 rows in set (0.00 sec)
Here the first argument of th query specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. Therefore it retrieves the rows from 3 - 7 from the student table.
We can also return the values from the beginning of the result set by specifying the number of rows in a single argument as follows.
mysql> select * from student limit 5;
+--------+---------+-------+------------------+---------+
studid name marks address phone
+--------+---------+-------+------------------+---------+
1 steve 100 5th cross street 2456987
2 david 98 welling street 547896
3 michael 75 edinburgh 2598234
4 jack 82 victoria street 2436821
5 anne 100 downing street 2634821
+--------+---------+-------+------------------+---------+
5 rows in set (0.08 sec)
The above query will retrieve the first five rows of the student table.
We can select a particular column to display, regretting the entire rows. Suppose you want to see the name of the students alone we can use the below query.
mysql> select name from student;
+---------+
name
+---------+
steve
david
michael
jack
anne
steve
anne
mille
+---------+
8 rows in set (0.27 sec)
We can also select multiple columns, separated by commas as given in the below query.
mysql> select name, marks from student;
+---------+-------+
name marks
+---------+-------+
steve 100
david 98
michael 75
jack 82
anne 100
steve 75
anne 80
mille 98
+---------+-------+
8 rows in set (0.03 sec)
In the above query, we have selected both name and marks from the table student
In the preceding examples, the query for selected rows are displayed in no particular order. We can also select the rows to display in an ordered format using ORDER BY Clause.
The following example query will sort the rows in an ascending order based on the marks.
mysql> select name, marks from student order by marks;
+---------+-------+
name marks
+---------+-------+
michael 75
steve 75
anne 80
jack 82
david 98
mille 98
steve 100
anne 100
+---------+-------+
8 rows in set (0.03 sec)
We can also sort the orders in descending order. In the below example query the marks are sorted in descending order.
mysql> select name, marks from student order by marks desc;
+---------+-------+
name marks
+---------+-------+
steve 100
anne 100
david 98
mille 98
jack 82
anne 80
michael 75
steve 75
+---------+-------+
8 rows in set (0.00 sec)
Next we can see how to sort the multiple columns.
We can also sort multiple columns in different directions as given in the below query.
mysql> select name, marks, address from student order by name,
marks desc;
+---------+-------+------------------+
name marks address
+---------+-------+------------------+
anne 100 downing street
anne 80 edinburgh
david 98 welling street
jack 82 victoria street
michael 75 edinburgh
mille 98 victoria street
steve 100 5th cross street
steve 75 downing street
+---------+-------+------------------+
8 rows in set (0.00 sec)
Here we have selected three columns name, marks and address. In this query we have sorted the column name alone in ascending order and we have additionally mentioned marks in descending order.
So if there are same names, the highest mark will be taken as the first priority. In the above example query, there are 2 anne, so the anne with highest mark will be displayed first
We can select a particular row using the WHERE clause statement. We can also check any condition using WHERE clause or keyword. Where condition comes handy when we come across a big table having huge volume of data but we might want to see only small number of rows satisfying a condition.
The select where syntax is
SELECT what_to_select FROM tbl_name WHERE conditions_to_satisfy;
Here the conditions_to_satisfy specifies one or more conditions that rows must satisfy to qualify for retrieval.
Let's see an example query for retrieving a single student data using the WHERE clause.
mysql> select * from student where name = 'jack';
+--------+------+-------+-----------------+---------+
studid name marks address phone
+--------+------+-------+-----------------+---------+
4 jack 82 victoria street 2436821
+--------+------+-------+-----------------+---------+
1 row in set (0.00 sec)
Here in the above example query we have retrieved a single student details. Suppose if we want to retrieve the student's details who have secured more than 90 marks, we can use the below query.
mysql> select * from student where marks > 90;
+--------+-------+-------+------------------+---------+
studid name marks address phone
+--------+-------+-------+------------------+---------+
1 steve 100 5th cross street 2456987
2 david 98 welling street 547896
5 anne 100 downing street 2634821
8 mille 98 victoria street 1236547
+--------+-------+-------+------------------+---------+
4 rows in set (0.05 sec)
Sometimes we may need to look for the table with a certain matching character. In MySQL we use LIKE or NOT LIKE operator for comparison. In MySQL the patterns are case-insensitive by default.
Let us consider an example query to display the student names starting with the letter M.
mysql> select * from student where name like 'm%';
+--------+---------+-------+-----------------+---------+
studid name marks address phone
+--------+---------+-------+-----------------+---------+
3 michael 75 edinburgh 2598234
8 mille 98 victoria street 1236547
+--------+---------+-------+-----------------+---------+
2 rows in set (0.01 sec)
In the above example query, it will list all the names that starts with the letter M from the table student.
The following example query will list the names that ends with letter e.
mysql> select * from student where name like '%e';
+--------+-------+-------+------------------+---------+
studid name marks address phone
+--------+-------+-------+------------------+---------+
1 steve 100 5th cross street 2456987
5 anne 100 downing street 2634821
6 steve 75 downing street 2874698
7 anne 80 edinburgh 2569843
8 mille 98 victoria street 1236547
+--------+-------+-------+------------------+---------+
5 rows in set (0.00 sec)
We can also list the names that contains a specific letter anywhere. The following example query will list the names that contains "a".
mysql> select * from student where name like '%a%';
+--------+---------+-------+-----------------+---------+
studid name marks address phone
+--------+---------+-------+-----------------+---------+
2 david 98 welling street 547896
3 michael 75 edinburgh 2598234
4 jack 82 victoria street 2436821
5 anne 100 downing street 2634821
7 anne 80 edinburgh 2569843
+--------+---------+-------+-----------------+---------+
5 rows in set (0.00 sec)
Suppose if we want to find the names that contain exactly five characters, we use a special character "_"(underscore). The following query will list all the five letter names from the table student.
mysql> select * from student where name like '_____';
+--------+-------+-------+------------------+---------+
studid name marks address phone
+--------+-------+-------+------------------+---------+
1 steve 100 5th cross street 2456987
2 david 98 welling street 547896
6 steve 75 downing street 2874698
8 mille 98 victoria street 1236547
+--------+-------+-------+------------------+---------+
4 rows in set (0.00 sec)
Group By :
The Group by clause is used to display the rows and columns grouped by selective columns. It can be used to perform the aggregate functions, such as count().
The following example query will list the name of the student and also count the repeative names using Group By clause in the select statement.
mysql> select name, count(name) from student group by name;
+-------+-------------+
name count(name)
+-------+-------------+
anne 2
david 1
jack 1
mille 1
steve 2
+-------+-------------+
5 rows in set (0.03 sec)
The below query will display the name and sum of marks of the student using groupby clause.
mysql> select name,sum(marks),count(*) from students group by name;
+----------+------------+----------+
name sum(marks) count(*)
+----------+------------+----------+
anne 175 2
maichael 82 1
mike 182 2
rock 100 1
steve 175 2
+----------+------------+----------+
5 rows in set (0.00 sec)

Saturday, February 2, 2008

MYSQL PART I

Database :
A database is a collection of data that is organized so that its contents can be easily accessed, managed and updated. The software used to manage and query a database is known as a Database Management System (DBMS). Then came the concept of Relational Database Management System(RDBMS). Relational database is a database where data are stored in more than one table, each one containing different types of data. The different tables can be linked so that information from the separate files can be used together. This is explained below using an example.

Example :
Consider the Student's personal information and the test marks in a school. Suppose the student's infomation and test results are stored seperately, we can get information regarding the student's personal information like Address from the first file. And also a student's mark at a test can be obtained from the other file.
But consider a situation where we want to get the Address of a student as well as his marks. These things become hard when we have a large volume of data. If we have a studentID stored in two files then we can easily relate the details and recollect them.
In relational databases, a table is a set of data elements(cells) that is organized, defined and stored using a model of horizontal rows and vertical columns. A table has a specified number of columns but can have any number of rows(i.e should have specified structure of date but can have any no. of data). Here every column is known as a field, every row is called as record.
MySQL
MySQL is one of the popular Relational Database Management System. Now let us see an example for a simple database which consists of a table. Consider the same example we took earlier, a student database. The table may have different fields such as StudID, Name, Marks, Address, Phone. These five fields constitutes a table named as student.StudID, Name are fileds and the particular row is a record.
StudID Name Marks Address Phone
1 steve 100 5th cross street 2456987
Now we slightly move to MySQL and see how to create database, use database and remove database
The following will not be needed if you have installed MySQL as a service.
Starting MySQL using command line:
Lets see how to start MySQL from the windows command line manually.
To start the mysqld from the command line, first you should open a console window i.e., Start -> Run.., type cmd or command to open the console window. After opening the console window, enter the path where your MySQL is installed. For example:
C:\> "C:Program Files\MySQL\MySQL Server 4.1\bin"
After giving the path, start the MySQL as given below:
C:\Program Files\MySQL\MySQL Server 4.1\bin> mysqld
The version depends upon the mysql server you have installed. The path may also vary depending on the MySQL installation on your system.
You can stop the MySQL server using the below command:
C:\> "C:\Program Files\MySQL\MySQL Server 4.1\bin\mysqladmin" -u root shutdown
The above commands will help you to start and stop the MySQL server.
Connecting MySQL server :
There are three ways to connect to a MySQL server. They are:
Command Prompt
MySQL Command Line Client
External MySQL Tools
Command Prompt :
You can connect MySQL from your Console window i.e., Start -> Run.., type cmd or command to open the Command prompt window.
After opening the console window, enter the path where your MySQL is installed. For example:
C:\> "C:Program Files\MySQL\MySQL Server 4.1\bin"
After giving the path, enter the below command to connect to MySQL server:
C:\Program Files\MySQL\MySQL Server 4.1\bin> mysql.exe -u root
The path may vary depending on the MySQL installation on your system. Instead of root you can also connect by giving your username.
MySQL Command Line Client :
To connect a MySQL server using the command line client, go to
Start -> Programs -> MySQL -> MySQL Server 4.1 -> MySQL Command Line Client. The command line client window will be opened and enter the password to start your queries.
External MySQL Tools :
You can also get connected to MySQL, using external tool like MySQL Query Browser.
Before going to create a database check whether there is any database with the name you are going to create. Check this by the following SHOW statement:
mysql> show databases;
This query will list the available databases. Please note that MySQL is case insensitive. So you can give the query with different cases also. So show dataBASES; , SHOW dataBASES; will also work.
Once you have confirmed that you don't have a database with the name you intended to create, then you can create your own database by,
mysql> create database sample;
Please note that only in Unix the database name is case sensitive. The above query will create an empty database and it wouldn't contain any tables.
If you want to create tables for a database first you have to select the database. For selecting a database you have to enter the following query :
mysql> USE sample;
Database changed
Here sample is the database you want to select. The USE command dosen't need a semicolon at the end of the query.
You can use the following command to view the current database that you're connected to:
mysql> select database();
+------------+
database()
+------------+
sample
+------------+
Understand the difference between Use database and select database() as the former is selecting a database and the later one is displaying the currently selected one. After selecting the database you can create tables and other such operations.
Note : You have to select the database using the USE statement everytime you are entering into Mysql server or when you want to change the database.
If you type the following query you can see an information like Empty set (ie.,) there are no tables in the selected database.
mysql> show tables;
Empty set (0.00 sec)
Database can be removed or deleted using the DROP statement. The following example deletes the database sample.
mysql> drop database sample;
Query OK, 1 row affected (0.05 sec)
This query will delete the database sample. The query will permanently remove the database.
DROP DATABASE drops all tables in the database and deletes the database. Once the DROP command is used, then we cannot use that database. So, we should be careful with this statement.
Data types :
Definition : Data type is the characteristic of columns and variables that defines what types of data values they can store. The characteristic indicating whether a data item represents a number, date, character string, etc.
Data types are used to indicate the type of the field we are creating into the table. MySQL supports a number of datatypes in three important categories:
Numeric types
Date and Time types
String(Character) types
Before creating a table, identify whether a column should be a text, number, or date type. Each column in a table is made of a data type. The size of the value should be the smallest value depending upon the largest input value.
For example, if the number of students in a school are in hundreds set the column as an unsigned three-digit SMALLINT(allowing for up to 999 values).
We should be concise in inserting a string of five characters long into a char(3) field, the final two characters will be truncated. It is better to set the maximum length for text and number columns as well as other attributes such as UNSIGNED.
Square brackets ('[' and ']') indicate optional parts of type definitions.
Now we slightly move to the overview of MySQL datatypes.
Numeric Datatypes :
The numeric data types are as follows:
BIT TINYINT BOOLEAN SMALLINT MEDIUMINT INT INTEGER BIGINT
FLOAT DOUBLE DECIMAL
Lets see the numeric datatypes briefly.
BIT :
BIT is a synonym for TINYINT(1).
TINYINT[(M)] :
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
BOOL, BOOLEAN :
These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
SMALLINT :
A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.
MEDIUMINT :
A medium-sized integer. The signed range is -8388608 to 8388607. The unsigned range is 0 to 16777215.
INT :
A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned range is 0 to 4294967295.
INTEGER :
This type is a synonym for INT.
BIGINT :
A large integer. The signed range is -9223372036854775808 to 9223372036854775807. The unsigned range is 0 to 18446744073709551615.
FLOAT :
A small(single-precision) floating-point number. The values are from 3.402823466E+38 to -1.175494351E-38, 0, and 1.175494351E-38 to 3.402823466E+38.
DOUBLE :
A normal-size(double-precision) floating-point number. The values are from 1.7976931348623157E+308 to -2.2250738585072014E-308, 0, and 2.2250738585072014E-308 to 1.7976931348623157E+308.
DECIMAL :
The maximum number of digits(M) for DECIMAL is 64.
Date and Time Data Types :
DATE TIME DATETIME TIMESTAMP YEAR
DATE :
A Date. The range is 1000-01-01 to 9999-12-31. The date values are displayed in YYYY-MM-DD format.
TIME :
A Time. The range is -838:59:59 to 838:59:59. The time values are displayed in HH:MM:SS format.
DATETIME :
A Date and Time combination. The range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59. The datetime values are displayed in YYYY-MM-DD HH:MM:SS format.
TIMESTAMP :
A Timestamp. The range is 1970-01-01 00:00:01 UTC to partway through the year 2037. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation.
YEAR :
A Year. The year values are displayed either in two-digit or four-digit format. The range of values for a four-digit is 1901 to 2155. For two-digit, the range is 70 to 69, representing years from 1970 to 2069.
For all the date and time columns, we can also assign the values using either string or numbers.
String data types :
CHAR VARCHAR TINYTEXT TEXT BLOB MEDIUMTEXT LONGTEXT
BINARY VARBINARY ENUM SET
CHAR() :
It is a fixed length string and is mainly used when the data is not going to vary much in it's length. It ranges from 0 to 255 characters long. While storing CHAR values they are right padded with spaces to the specified length. When retrieving the CHAR values, trailing spaces are removed.
VARCHAR() :
It is a variable length string and is mainly used when the data may vary in length. It ranges from 0 to 255 characters long. VARCHAR values are not padded when they are stored.
TINYTEXT, TINYBLOB :
A string with a maximum length of 255 characters.
TEXT :
TEXT columns are treated as character strings(non-binary strings). It contains a maximum length of 65535 characters.
BLOB :
BLOB stands for Binary Large OBject. It can hold a variable amount of data. BLOB columns are treated as byte strings(binary strings). It contains a maximum length of 65535 characters.
MEDIUMTEXT, MEDIUMBLOB :
It has a maximum length of 16777215 characters.
LONGTEXT, LONGBLOB :
It has a maximum length of 4294967295 characters.
BINARY :
The BINARY is similar to the CHAR type. It stores the value as binary byte strings instead of non-binary character strings.
VARBINARY :
The VARBINARY is similar to the VARCHAR type. It stores the value as binary byte strings instead of non-binary character strings.
ENUM() :
An enumeration. Each column may have one of a specified possible values. It can store only one of the values that are declared in the specified list contained in the ( ) brackets. The ENUM list ranges up to 65535 values.
SET() :
A set. Each column may have more than one of the specified possible values. It contains up to 64 list items and can store more than one choice. SET values are represented internally as integers.
If CHAR and VARCHAR options are used in the same table, then MySQL will automatically change the CHAR into VARCHAR for compatability reasons. The ( ) bracket allows to enter a maximum number of characters that will be used in the column.

Saturday, January 12, 2008

Introduction to Microsoft Access

Microsoft Access Launching
Introduction
Microsoft Access is a computer application used to create and manage computer-based databases on desktop computers and/or on connected computers (a network). Microsoft Access can be used for personal information management (PIM), in a small business to organize and manage all data, or in an enterprise to communicate with servers.

Like any other computer application, in order to use Microsoft Access, you must first open it. There are various ways this can be done. Microsoft Access is a classic computer application and it gets launched like the usual products you have probably been using. As such, to start this program, you could click Start -> (All) Programs -> Microsoft Access:

As a regular member of the Microsoft Office suite of applications, if your installation created a sub-menu on the Start menu, you could click Start -> New Office Application and proceed from the New dialog box.
Although Microsoft Office 97 and Microsoft Office 2000 get installed in the C:\Program Files\Microsoft Office folder, they treat the shortcuts that launch them differently. The applications that are part of Microsoft Office 97 designate their shortcuts with full names and these are installed in the Microsoft Office folder. Microsoft Office 2000 (Premium) uses shortcut names to designate its shortcuts and they are installed in the Microsoft Office\Office folder. This means that you could launch an application from Windows Explorer or My Computer. Therefore, in order to launch Microsoft Access, locate its shortcut in Windows Explorer or My Computer and double-click it:


If you have a Microsoft Access database such as an E-Mail attachment, a file on a floppy disk, on the network, or in any other means, once you see its icon, you can double-click it. Not only will this action launch Microsoft Access, but also it will open the file.You can also launch Microsoft Access from a shortcut. If you happen to use the software on a regular basis, you can create a shortcut on your desktop or on the Quick Launch area. Many users also take advantage of the Microsoft Office Shortcut Bar. Sometimes, the icon you need will not be there; in that case you should insert it manually.If you are working on a network of related computers, your database may be located in another computer. In this case the network or database administrator would create a link or shortcut to the drive that is hosting the database. You can then click or double-click this link or shortcut to open the database and, as a result, launch Microsoft Access.
Microsoft Access Shortcuts
Whenever you find out that you are using a particular program or file most regularly, you should have an icon on the desktop that can lead you to it quickly. This icon is called a shortcut. There are various techniques used to create a shortcut. Probably the first thing you should find out is where your application is located. You can find out by doing a search on the computer. Except on Microsoft Windows 95, you can create a shortcut from the Programs menu.
By default, the shortcuts on the Microsoft Office 97 applications are located in the C:\Program Files\Microsoft Office folder. And these shortcuts hold the same names as their respective programs; those will be Microsoft Word, Microsoft Excel, Microsoft PowerPoint, etc. The shortcuts of the Microsoft Office 2000 applications are located in the C:\Program Files\Microsoft Office\Office folder. These shortcuts use another naming convention. They are Msaccess, Winword, Excel, or Frontpg, just to name a few.To create a shortcut from Windows Explorer or My Computer, you can right-click the icon or the shortcut of the application, position your mouse on Send To, and click Desktop (Create Shortcut).To create a shortcut from the Start menu, click Start -> (All) Programs. When the program appears, you can right-click it, position the mouse pointer on Send To and click Desktop (Create Shortcut).
Practical Learning: Creating a Shortcut
Right-click on an empty area of the Desktop -> New -> Shortcut


On the first page of the wizard, click the Browse button
Make sure the Look In combo box is displaying the C: drive
Double-click Program Files
Double-click Microsoft Office
If you are using Microsoft Access 97, click Microsoft Access. If you are using Microsoft Access 2000, double-click Office. Then click Msaccess:


Click Open
Click Next

If you are using Microsoft Access 97, notice the name of the shortcutIf you are using Microsoft Access 2000 or later, change the name of the shortcut to Microsoft Access:


Click Finish