Wednesday, March 26, 2014

How to install MySQL & other tools

Introduction


Download MySQL

Uninstall any previous versions through Control Panel prior to install.

MySQL is 'Open Source' software that is undergoing constant development.

At the time of writing this guide there are two later versions available
1. MySQL 5.5 is the current development release series
2. MySQL 5.1 is the current General Availability (Production) release series

I recommend you dowload the latest General Availability (GA) version as it has undergone extensive testing and is considered 'stable'.
To check which is the latest GA version click here - http://dev.mysql.com/doc/refman/5.1/en/choosing-version.html

The download you need for Windows is 'MSI Installer' for your system
mysql-essential-X.XX.XX-win32.msi - for 32 bit Windows OR
mysql-essential-X.XX.XX-winx64.msi - for 64 bit Windows


You must exit all other programs, in particular Anti Virus programs.

The install outlines here was on a 64bit system and is identical to 32 bit install.

Should you experience errors with the install - see NOTES below

Step 1

Navigate to the folder you downloaded to and click on install package.



Step 2

You may receive this security warning - click Run


Step 3

Click Next >


Step 4

You may select Typical if you are have a limited hard disk capacity.
I recommend Complete install.
Click Next >


Step 5

You are now ready to install - click Install


Step 6

Click Next >


Step 7

Click Next >


Step 8

Tick Configure the MySQL Server now
Registration is optional.
Click Finish


Step 9

Click Next >


Step 10

Your will only see this screen if you have previously installed or patrially installed this version of MySQL
If not previously installed go to Step 11
Select Reconfigure Instance then click Next >


Step 11

Select Detailed Configuration then click Next >


Step 12

Select Developer Machine then click Next >


Step 13

Select Non-Transactional Database Only then click Next >


Step 14

Select Decision Support (DSS)/OLAP then click Next >


Step 15

Select both (default) options: Enable TCP/IP Networking and Enable Strict Mode then click Next >


Step 16

Select (Default) Standard CharacteSet then click Next >


Step 17

Select both options: Install As Windows Service and Include Bin Directory in Windows Path then click Next >

Note: if you have installed an earlier version of MySQL the default Service Name: MySQL will not be available as it is already in use.
You MUST uninstall previous version to use the default Service Name


Step 18

If you have a previous install you must enter Current root password - if no previous install you will not see this
Enter New root password and Confirm
Make sure you record the Root Password
Note: The default username is root.
It is recommended to change this setting up PHPMyAdmin or MySQL Command Line Client (advanced)
Click Next >


Step 19

Click Execute to configure your database server.



NOTES
Should you receive any error messages when installing then cancel the install
Go to 'Control Panel' and remove MySQL
Before reinstalling shut down & restart then close all programs, including Anti Virus and reinstall.
If problem persists, more likely with 64 bit install, try downloading the current development release and installing.
Help can also be found at http://www.mysql.com/

NOTE: This drove me nuts for a while creating all sorts of errors in php code I was using
For some reason Microsoft thought we all required Military grade security and enabled 'Strict Mode' by default in MySQL.
This would only be required by securty & government agencies, eg my ISP disable on their server.
You can surf around on Google to read up on it & the various complex methods to disable it or keep reading.

To disable Strict Mode the easy way
Open your my.ini file
located at C:\Program Files\MySQL\MySQL Server 5.5\my.ini in your text editor (eg notepad)
Use control F (push Ctrl & F keys on keyboard together) and search for 'Strict'
locate this

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Change to this

# Set the SQL mode to strict
#sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

or you can delete these lines altogether

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

by placing the hash (#) in front it disables Strict Mode

I recommend the (#) method so the lines are still there if you ever need enable 'Strict Mode' again (if you become a high security programmer!)

Then simply save the file in it's original location (eg click File then 'Save').


Simple way to import data into SQL Server

Overview

SQL Server Management Studio (SSMS) provides the Import Wizard task which you can use to copy data from one data source to another.  You can choose from a variety of source and destination data source types, select tables to copy or specify your own query to extract data, and save your work as an SSIS package.  In this section we will go through the Import Wizard and import data from an Excel spreadsheet into a table in a SQL Server database. 

1. Enter the data into an Excel spreadsheet

  • First, enter the data into an Excel spreadsheet.
  • In this example, the default spreadsheet name, Sheet1, has been retained, but if you rename the sheet (to the name you want for the table in the database, for example), that name will be automatically used in the import process (at Step 6).
Small demonstration Excel spreadsheet ready for transfer to a SQL database

Excel spreadsheet ready to export to a SQL table.

2. Start the SQL Import and Export Wizard

  • Next, in Windows, start the Import and Export Wizard at Start / All Programs / Microsoft SQL Server 2008/ Import and Export Data.
  • The Welcome page appears. Click Next.
SQL Import and Export Wizard in the Windows Start menu

Windows menu showing SQL Server Import and Export Wizard

OR  Right click on the you needed database in the Object Explorer, select Tasks, then Import Data from the context menu to launch the Import Wizard. 

Welcome page of the SQL Server Import and Export Wizard

3. Chose your Excel spreadsheet as the Data Source

  • In the Data Source dropdown of the Choose a Data Source page, select Microsoft Excel.
  • In the Excel file path box, specify the file path to the Excel spreadsheet.
  • Select the the version in the Excel version dropdown.
  • Make sure that First row has column names is checked.
  • Click Next.


Chose a Data Source page in the SQL Server Import and Export Wizard


4. Chose your SQL database as the destination

  • In the Destination dropdown list, accept the default setting of SQL Server Native Client 10.0.
  • In the Server name dropdown list, enter the name of the server. The example is a remote server, so the IP address and port of the server were specified.
  • Chose the Authentication type. The example is a remote server, so SQL Server authentication, with a user name and password, is required.
  • In the Database dropdown list, select or type the name of the database.
  • Click Next.
Chose a Data Destination page in the SQL Server Import and Export Wizard


5. Specify how to copy the data

  • The default option, Copy data from one or more tables or views, works for this example.
  • If you want to try the second option, Write a query to specify the data to transfer, the followinglolcode snippet may be instructive:
CAN HAS SQL?
DBASE IZ GETDB('db/demo.db')
FUNNAHS IZ DBUCKET(&DBASE&,"CAN I PLZ GET * ALL UP IN lollit")
IM IN UR FUNNAHS ITZA TITLE
    VOTEZ IZ &TITLE#ups& - &TITLE#downs&
  • Click Next.
 Specify Table Copy or Query page in the SQL Server Import and Export Wizard

6. Select the source tables and views

  • The default settings as shown work in this example.
  • In the Destination column, you can specify a different name for the table in the SQL database if you choose.
  • Click Preview to see how your data will appear in the destination table.
  • You can click Edit Mappings to change how your data is assigned at the destination table, but it shouldn't be necessary in this example since you entered the data into the Excel spreadsheet yourself.
  • Click Next.
Select Source Tables and Views page in the SQL Server Import and Export Wizard


7. Run the "Package"

The following message appears at the bottom of the Run Package page: In SQL Server Express, Web, or Workgroup, you can run the package that the Import and Export Wizard creates, but cannot save it. To save packages that the wizard creates, you must upgrade to SQL Server Standard, Enterprise, Developer or Evaluation. A "package" is all of the settings that your have configured so far. In the commercial versions of SQL Server, you can save the package for reuse so you don't have to enter all of the settings the next time you run the wizard. In the Express (free) version of Microsoft SQL Server 2008 Management Studio, you must re-enter all of the settings every time you run the SQL Server Import and Export wizard.
  • Click Next.
Run Package page in the SQL Server Import and Export Wizard

8. Verify that the package executed successfuly

  • Click Report to view useful information about the data transfer process.
  • Click Close.
The execution was successful page in the SQL Server Import and Export Wizard

9. View the new table in SQL Server Management Studio

  • View your new table by opening Microsoft SQL Server 2008 Management Studio at Start / All Programs / Microsoft SQL Server 2008/ Import and Export Data.
The new table, dbo.Sheet1$, in Microsoft SQL Server Management Studio


Successfully imported table in SQL Server Management Studio


You can also use the Import and Export Wizard to export data from a table in SQL Server to an Excel spreadsheet.

Thursday, March 6, 2014

DBMS II Practical Workbook Answers

Worksheet  3

DDLs in T_SQL
1. Bank schema

create table Bank(
code varchar(50),
name varchar(50) not null ,
descrip varchar(50),
constraint pk_Bank primary key(code)
)


create table Branch (
bank_code varchar(50),
branch_no varchar(50),
name varchar(50),
addr varchar(50),
constraint pk_Branch primary key(bank_code,branch_no),
constraint fk_Branch foreign key(bank_code) references Bank (code)
)


create table Account (
acc_no varchar(50),
balance float,
bank_code varchar(50),
branch_no varchar(50),
type_code varchar(50),


constraint pk_Account primary key(acc_no),
constraint fk1_Account foreign key(bank_code,branch_no)
references Branch (bank_code,branch_no),
constraint fk2_Account foreign key(type_code) references
AccountType (code),
constraint chk_Account check (balance >= 0)
)


create table AccountType (


code varchar(50),
name varchar(50),
decrip varchar(50),
constraint pk_AccountType primary key(code)
)
create table Saving (
code varchar(50),
interest_rate float,
constraint pk_Saving primary key(code),
constraint fk_Saving foreign key(code) references AccountType (code),
constraint chk_Saving check (interest_rate >= 0)
)


create table CurrentAcc (
code varchar(50),
max_cheque float,
constraint pk_CurrentAcc primary key(code),
constraint fk_CurrentAcc foreign key(code) references AccountType (code)
)


create table Balongs_to (
acc_no varchar(50),
cus_no varchar(50),
constraint pk_Balongs_to primary key(acc_no,cus_no),
constraint fk_Belongs_to foreign key(acc_no) references Account (acc_no),
constraint fk2_Belongs_to foreign key(cus_no) references Customer (cus_no),
)


create table Customer (
cus_no varchar(50),
NIC varchar(15),
name varchar(50)not null,
addr varchar(50),
phone varchar(12),
PIN char(4),
constraint pk_Customer primary key(cus_no),
constraint chk_Customer check (PIN like '[0-9][0-9][0-9][0-9]'),
constraint chk2_Customer check ( NIC like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][V,X]')
)


create table Has (
acc_no varchar(50),
trans_id varchar(50),
Trans_type varchar(20),


constraint pk_Has primary key(acc_no),
constraint fk_Has foreign key(acc_no) references Account (acc_no),
constraint fk2_Has foreign key(trans_id) references Transactions (trans_id),
constraint chk_Has check(Trans_type in('Credit','debit'))
)


create table Transactions (


trans_id varchar(50),
amount float,
descrip varchar(50),
executed_by varchar(50),
dateAndtime datetime default getdate(),
constraint pk_Transactions primary key(trans_id),
constraint chk_Transactions check(executed_by in('ATM','Teller','Bank','Standing order','Cheque','On-Line','Other'))
)
2. Library schema

create table Book (
item_no varchar(50),
title varchar(50) not null,
decrip varchar(50),
constraint pk_Books primary key(item_no),
constraint chk_Books check(item_no like 'B%')
)

create table Written_by (
item_no varchar(50),
author_id int,
constraint pk_Written_by primary key(item_no,author_id),
constraint fk_Witten_by foreign key(item_no) references Books (item_no),
constraint fk2_Witten_by foreign key(author_id) references Author (author_id)
)

create table Author (
author_id int IDENTITY(1,1),
fname varchar(50),
lname varchar(50),
other varchar(50),
constraint pk_Author primary key(author_id)

create table TextBooks (
item_no varchar(50),
semester varchar(20),
year int,
section varchar(50),


constraint pk_TextBooks primary key(item_no),
constraint fk_TextBooks foreign key(item_no) references Books (item_no),
constraint chk_TextBooks check(section in('Lecture','Lab','Tutorial')),
constraint chk2_TextBooks check(year between '1999' and '3000')
)

create table CopyText (


access_no varchar(50),
item_no varchar(50),
status varchar(15),
constraint pk_CopyText primary key(access_no),
constraint fk_CopyText foreign key(item_no) references TextBooks (item_no),
constraint chk_CopyText check(status in('Borrowed','Stolen','Available'))
)

create table PublishedBooks (
item_no varchar(50),
edition varchar(15),
constraint pk_PublishedBooks primary key(item_no),
constraint fk_PublishedBooks foreign key(item_no) references Books (item_no)
)

create table PublishedBooksType (
ISBN varchar(50),
item_no varchar(50),
cover varchar(15),
published_yr int,
publisher varchar(50),
constraint pk_PublishedBooksType primary key(ISBN),
constraint fk_PublishedBooksType foreign key(item_no) references PublishedBooks (item_no),
constraint chk_PublishedBooksType check(cover in('Soft Cover','Hard Cover')),
constraint chk2_PublishedBooksType check(published_yr between 1000 and 3000)
)

create table CopyPublishedBooksType(
access_no varchar(50),
ISBN varchar(50),
status varchar(15),
constraint pk_CopyPublishedBooksType primary key(access_no),
constraint fk_CopyPublishedBooksType foreign key(ISBN) references PublishedBooksType (ISBN),
constraint chk_CopyPublishedBooksType check(status in('Borrowed','Stolen','Available'))
);

create table Periodicals (
item_no varchar(50),
title varchar(50) not null,
decrip varchar(50),
frequency varchar(50),
publisher varchar(50),
type varchar(10),
constraint pk_Periodicals primary key(item_no),
constraint chk_Periodicals check(item_no like 'P%'),
constraint chk2_Periodicals check(type in('Magazine','Newspaper'))
)

create table PeriodicalType (
item_no varchar(50),
date datetime,
constraint pk_PeriodicalType primary key(item_no,date),
constraint fk_PeriodicalType foreign key(item_no) references Periodicals(item_no)
)

create table CopyPeriodicalType (
access_no varchar(50),
status varchar(15),
item_no varchar(50),
date datetime,
constraint pk_CopyPeriodicalType primary key(access_no),
constraint fk_CopyPeriodicalType foreign key(item_no,date) references PeriodicalType(item_no,date),
constraint chk_CopyPeriodicalType check(status in('Borrowed','Stolen','Available'))

create table SoftwareAndManuals (
item_no varchar(50),
title varchar(50) not null,
decrip varchar(50),
manufacture varchar(50),
version varchar(50),
constraint pk_SoftwareAndManuals primary key(item_no),
constraint chk_SoftwareAndManuals check(item_no like 'S%')
)

create table CopySoftwareAndManuals (
access_no varchar(50),
status varchar(15),
item_no varchar(50),
constraint pk_CopySoftwareAndManuals primary key(access_no),
constraint fk_CopySoftwareAndManuals foreign key(item_no) references SoftwareAndManuals (item_no),
constraint chk_CopySoftwareAndManuals check(status in('Borrowed','Stolen','Available'))
)

3. SLIIT schema

create table Campus (
code varchar(50),
name varchar(50) not null,
addr varchar(50),
constraint pk_Campus primary key(code)
)

create table Batch (
id varchar(50),
groupNo varchar(50) not null,
maximum int,
section varchar(50),
code varchar(50),
prg_code varchar(50),
constraint pk_Batch primary key(id),
constraint fk_Batch foreign key(code) references Campus (code),
constraint fk2_Branch foreign key(prg_code) references Program (prg_code)
)

create table Program (
prg_code varchar(50),
name varchar(50),
special varchar(50),
descrip varchar(50),
constraint pk_Program primary key(prg_code),
)

create table Batch_Semester (
batch_id varchar(50),
acadamic_sem_no int,
constraint pk_Batch_Semester primary key(batch_id,acadamic_sem_no),
constraint fk_Batch_Semester foreign key(batch_id) references Batch(id),
constraint fk2_Batch_Semester foreign key(acadamic_sem_no) references Acadamic_Semester (acadamic_sem_no),
)

create table Semester (
prgm_code varchar(50),
sem_no int,
semester varchar(50) not null,
year int not null,
constraint pk_Semester primary key(prgm_code,sem_no),
constraint fk_Semester foreign key(prgm_code) references Program (prg_code)
)

create table Acadamic_Semester (
acadamic_sem_no int,
year int,
prgm_code varchar(50),
sem_no int,
constraint pk_Acadamic_Semester primary key(acadamic_sem_no),
constraint fk_Acadamic_Semester foreign key(prgm_code,sem_no) references Semester (prgm_code,sem_no),
)

create table Student (
reg_no varchar(50),
name varchar(50),
address varchar(50),
phone varchar(10),
constraint pk_Student primary key(reg_no)
)

create table Register (
reg_no varchar(50),
batch_id varchar(50),
acadamic_sem_no int,
date datetime DEFAULT GETDATE(),
constraint pk_Register primary key(reg_no,batch_id,acadamic_sem_no),
constraint fk_Register foreign key(reg_no) references Student (reg_no),
constraint fk2_Register foreign key(batch_id,acadamic_sem_no) references Batch_Semester (batch_id,acadamic_sem_no)

)



Worksheet  4

Objective: Moving Data


Export the data given in the excel sheets to the Library and Bank databases which is developed by you. You may use Data Transformation Services (Import/Export Wizard) and T-SQL scripts to do this. If you write any SQL or T-SQL scripts to load data to the tables, you should attach them to your solution.


1. Enter the data into an Excel spreadsheet

  • First, enter the data into an Excel spreadsheet.
  • In this example, the default spreadsheet name, Sheet1, has been retained, but if you rename the sheet (to the name you want for the table in the database, for example), that name will be automatically used in the import process (at Step 6).
Small demonstration Excel spreadsheet ready for transfer to a SQL database

Excel spreadsheet ready to export to a SQL table.

2. Start the SQL Import and Export Wizard

  • Next, in Windows, start the Import and Export Wizard at Start / All Programs / Microsoft SQL Server 2008/ Import and Export Data.
  • The Welcome page appears. Click Next.
SQL Import and Export Wizard in the Windows Start menu

Windows menu showing SQL Server Import and Export Wizard

OR  Right click on the you needed database in the Object Explorer, select Tasks, then Import Data from the context menu to launch the Import Wizard. 

Welcome page of the SQL Server Import and Export Wizard

3. Chose your Excel spreadsheet as the Data Source

  • In the Data Source dropdown of the Choose a Data Source page, select Microsoft Excel.
  • In the Excel file path box, specify the file path to the Excel spreadsheet.
  • Select the the version in the Excel version dropdown.
  • Make sure that First row has column names is checked.
  • Click Next.


Chose a Data Source page in the SQL Server Import and Export Wizard


4. Chose your SQL database as the destination

  • In the Destination dropdown list, accept the default setting of SQL Server Native Client 10.0.
  • In the Server name dropdown list, enter the name of the server. The example is a remote server, so the IP address and port of the server were specified.
  • Chose the Authentication type. The example is a remote server, so SQL Server authentication, with a user name and password, is required.
  • In the Database dropdown list, select or type the name of the database.
  • Click Next.
Chose a Data Destination page in the SQL Server Import and Export Wizard


5. Specify how to copy the data

  • The default option, Copy data from one or more tables or views, works for this example.
  • If you want to try the second option, Write a query to specify the data to transfer, the followinglolcode snippet may be instructive:
CAN HAS SQL?
DBASE IZ GETDB('db/demo.db')
FUNNAHS IZ DBUCKET(&DBASE&,"CAN I PLZ GET * ALL UP IN lollit")
IM IN UR FUNNAHS ITZA TITLE
    VOTEZ IZ &TITLE#ups& - &TITLE#downs&
  • Click Next.
 Specify Table Copy or Query page in the SQL Server Import and Export Wizard

6. Select the source tables and views

  • The default settings as shown work in this example.
  • In the Destination column, you can specify a different name for the table in the SQL database if you choose.
  • Click Preview to see how your data will appear in the destination table.
  • You can click Edit Mappings to change how your data is assigned at the destination table, but it shouldn't be necessary in this example since you entered the data into the Excel spreadsheet yourself.
  • Click Next.
Select Source Tables and Views page in the SQL Server Import and Export Wizard


7. Run the "Package"

The following message appears at the bottom of the Run Package page: In SQL Server Express, Web, or Workgroup, you can run the package that the Import and Export Wizard creates, but cannot save it. To save packages that the wizard creates, you must upgrade to SQL Server Standard, Enterprise, Developer or Evaluation. A "package" is all of the settings that your have configured so far. In the commercial versions of SQL Server, you can save the package for reuse so you don't have to enter all of the settings the next time you run the wizard. In the Express (free) version of Microsoft SQL Server 2008 Management Studio, you must re-enter all of the settings every time you run the SQL Server Import and Export wizard.
  • Click Next.
Run Package page in the SQL Server Import and Export Wizard

8. Verify that the package executed successfuly

  • Click Report to view useful information about the data transfer process.
  • Click Close.
The execution was successful page in the SQL Server Import and Export Wizard

9. View the new table in SQL Server Management Studio

  • View your new table by opening Microsoft SQL Server 2008 Management Studio at Start / All Programs / Microsoft SQL Server 2008/ Import and Export Data.
The new table, dbo.Sheet1$, in Microsoft SQL Server Management Studio


Successfully imported table in SQL Server Management Studio


You can also use the Import and Export Wizard to export data from a table in SQL Server to an Excel spreadsheet.


Worksheet  5

--Exercise 1.
Create a view in T-SQL (called Cust_Inf containing the following information of customers:
 Customer’s number, NIC, name,
 His/her account information: account number and account type’s name

Using the view above, query Mr. Sampath Wijesinghe’s account information.

create table Customer(
customer_number int primary key,
name varchar(100),
nic varchar(10),
);

create table Account(
account_number varchar(100) primary key,
account_type varchar(100),
customer_number int,
amount float,
constraint fk1 foreign key (customer_number) references Customer(customer_number),  

);

create view Cust_Inf(customer_number,name,nic,account_number,account_type)
as
select c.customer_number,c.name,c.nic,a.account_number,a.account_type
from Customer c,Account a
where c.customer_number = a.customer_number

select *
from Cust_Inf


-- Exercise 2
A policy of the bank is that a single customer cannot have more than 5 accounts. Write a DML trigger to ensure that this policy is enforced. Note that the customer can have more than 5 accounts in total from different banks.
Test your trigger with sample data.

create trigger trigger1
on Account
for insert,update
as
begin

            declare @customer_number int
            declare @count_ int

            select @customer_number = i.customer_number
            from Inserted i

            select @count_ = COUNT(*)
            from Account
            where customer_number = @customer_number

            if(@count_>5)
            begin
                        rollback transaction
            end
end

-- Exercise 3
Write a stored procedure, which takes the account number and returns the number of cheques processed for that account during the current month.
Test your stored procedure with sample data.

create table cheque
(
chequeNo int primary key ,
dates datetime,
account_number varchar(100),
constraint fk2 foreign key (account_number) references Account(account_number), 
);



select *
from cheque

create procedure count_cheques(@number varchar,@noOfCheque int output )
as
begin

            declare @months int
            select @months=month(getdate())

            select @noOfCheque = COUNT(*)
            from Account a,cheque c
            where  a.account_number=@number and a.account_number=c.account_number and c.dates = @months
end;
drop procedure count_cheques



-- Exercise 4:

Write a stored procedure that transfers funds between accounts. The input parameters include account number of source account, account number of destination account and amount to be transferred. Ensure that the transaction occurs within a single transaction. Also, ensure that appropriate information is updated in the Transaction table.
Test your stored procedure with sample data.
create procedure transactions (@sourseAccount int ,@destinationAccount int,@amount float)
as
begin

            declare @sourseAmount float
            declare @destinationAmount float

            select @sourseAmount=amount
            from Account a
            where a.account_number=@sourseAccount


            select @destinationAmount=amount
            from Account b
            where b.account_number=@destinationAccount

            if(@sourseAmount>@amount)
            begin
             
                        SET @destinationAmount=@destinationAmount+@amount
                        SET @sourseAmount = @sourseAmount-@amount

                        update Account
                        set amount=@sourseAmount
                        where account_number =@sourseAccount

                        update Account
                        set amount=@destinationAmount
                        where account_number =@destinationAccount
                        return;

            end

            else
            begin
                        rollback transaction
            end

end;


OAuth authorization server