Database

From QwikITedia

Jump to: navigation, search

Contents


MySQL

Install MySQL & PHP Support on Ubuntu

apt-get install mysql-server mysql-client libmysqlclient15-dev libapache2-mod-auth-mysql php5-mysql 
apt-get install phpmyadmin

Learn who is connected to MySQL

diazepam htdocs # mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 82
Server version: 5.0.54-log Gentoo Linux mysql-5.0.54

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> show processlist;
+----+-----------+-----------+-------+---------+------+-------+------------------+
| Id | User      | Host      | db    | Command | Time | State | Info             |
+----+-----------+-----------+-------+---------+------+-------+------------------+
| 79 | cactiuser | localhost | cacti | Sleep   |    0 |       | NULL             | 
| 82 | root      | localhost | NULL  | Query   |    0 | NULL  | show processlist | 
+----+-----------+-----------+-------+---------+------+-------+------------------+
2 rows in set (0.00 sec)

mysql>

Remove MySQL

sudo /etc/init.d/mysql stop
apt-get --purge remove mysql-server-5.0

MySQL CLI (Command Line Drive MySQL Administration)

Login

# [mysql dir]/bin/mysql -h hostname -u root -p

Create a database

mysql> create database [databasename];

List databases on the sql server.

mysql> show databases;

Switch to a database.

mysql> use [db name];

To see all the tables in the db.

mysql> show tables;

To see database's field formats.

mysql> describe [table name];

To delete a db.

mysql> drop database [database name];

To delete a table.

mysql> drop table [table name];

Show all data in a table.

mysql> SELECT * FROM [table name];
mysql> show columns from [table name];
mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";
mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';
mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;
mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";

Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
==== Return number of rows. ====
<pre>mysql> SELECT COUNT(*) FROM [table name];

Sum column.

mysql> SELECT SUM(*) FROM [table name];

Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Change a users password

# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;
* Recover a MySQL root password. Stop the MySQL server process. 
* Start again with no grant tables.
* Login to MySQL as root.
* Set new password.
* Exit MySQL and restart MySQL server.
<pre>
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Set a root password

# mysqladmin -u root password newpassword

Update a root password

# mysqladmin -u root -p oldpassword newpassword
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;

or

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

To update info already in a table

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';

Delete a row(s) from a table

mysql> DELETE from [table name] where [field name] = 'whatever';
==== Update database permissions/privilages
.
mysql> flush privileges;
==== Delete a column ====
<pre>mysql> alter table [table name] drop column [column name];

Add a new column to db

mysql> alter table [table name] add column [new column name] varchar (20);

Change column name

mysql> alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);

Make a column bigger

mysql> alter table [table name] modify [column name] VARCHAR(3)
;

Delete unique from table

mysql> alter table [table name] drop index [colmn name];

Load a CSV file into a table

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Dump all databases for backup

# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Dump one database for backup

# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql

Dump a table from a database

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql

Restore database (or database table) from backup

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql

Create Table - Example 1

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));

Create Table - Example 2

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');

PostGres

Remove PostGreSQL v8.2.27

apt-get --purge remove postgresql-8.2 postgresql-client-8.2 postgresql-client-common postgresql-common

Install PostgreSQL v8.3.x

apt-get install postgresql-8.3 postgresql-client-8.3 postgresql-client-common postgresql-common


Install PostgreSQL v8.4.x

sudo vi /etc/apt/sources.list
# Additionalrepos required to install PostgreSQL 8.4 on ubuntu for ICE - R.Esmonde 7/28/2010

deb http://us.archive.ubuntu.com/ubuntu hardy-backports main
deb http://us.archive.ubuntu.com/ubuntu hardy-updates main restricted universe
deb http://us.archive.ubuntu.com/ubuntu hardy-security main restricted universe
 apt-get update
apt-get install postgresql-8.4 postgresql-client-8.4 postgresql-client-common postgresql-common

Start or Stop Postgres 8.3

/etc/init.d/postgresql-8.3 start
/etc/init.d/postgresql-8.3 stop

PostgreSQL v8.3.x

  1. TOAD SQL
  2. phppgadmin
  3. pgAdmin111

Set DB root user Password

sudo -u postgres psql postgres
\password postgres

Create a Database

root@gotham:/etc/postgresql-common# psql -d postgres
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

CREATE a NEW DB
postgres=# create database halle;
CREATE DATABASE

Create a user

CREATE a NEW USER
postgres=# create user orinoco with password 'womble';
CREATE ROLE

Setup DB privileges

GRANT new USER some PRIVILEGES
postgres=# grant all privileges on database halle to orinoco;
GRANT

Test using GUI tool

  1. Name=hal
  2. Host=hal
  3. Port=5432
  4. MaintenaceDB=halle
  5. Username=orinoco
  6. Password=womble

Connect as a user from the Command Line

  1. -h is for HOSTNAME
  2. -p is for PORT
  3. -d the database you want to connect to
  4. -U the user you want to connect as
  5. -W force a Password prompt for the user
root@hal:/etc/postgresql/8.3/main# psql -h localhost -p 5432 -d zulu -U resmonde -W
Password for user resmonde:

Revoke privileges

REVOKE ALL PRIVILEGES ON halle FROM orinoco;

Delete a user

DROP USER orinoco;

Delete a Database

DROP DATABASE halle;

List Databases

psql -l

Reset Password

alter user vu2131 with password 'foobar';

Describe Commands

\d ~= desc

\dt Show Tables
\dT list datatypes
\df list functions
\di list indexes
\dv list views

PHPPGADMIN install

sudo apt-get install phppgadmin
sudo vi /usr/share/phppgadmin/conf/config.inc.php
$conf['extra_login_security'] = false;
sudo ln -s /etc/phppgadmin/apache.conf /etc/apache2/conf.d/phppgadmin.conf
# root@lapp:~# su -c 'createuser -P admin' postgres
# Enter password for new role: xxxxxxxxxx
# Enter it again:  xxxxxxxxxx
# Shall the new role be a superuser? (y/n) y
# CREATE ROLE
sudo /etc/init.d/postgres-8.3 restart
#allow from 127.0.0.0/255.0.0.0
allow from all
sudo vi /etc/postgresql/8.3/main/pg_hba.conf
# IPv4 local connections:
host    all         all         127.0.0.1/32          md5
host    all     all     10.5.5.0 255.255.255.0  password
sudo /etc/init.d/postgresql-8.3 restart

CLI Session as PostGres User

resmonde@myserver:~$ sudo -i
root@myserver:~#su postgres
postgres@myserver:/root$
postgres@myserver:/root$ psql -d postgres -U postgres -W
Password for user postgres: 
Welcome to psql 8.3.11, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

postgres=# \q

LDAP Authentication

  1. Ensure the user(s) that is trying to connect to the PostGres DB has an Active Directory (Archimedes Domain) account and that a user with this exact username exists within the PostGres database they are trying to connect to over LDAP - or this will NOT work.
    1. For example:: ddyve is a user in the Active directory and ddyve is a user with access to the PostGres database called datadyve


LDAPSEARCH is your friend

# ldapsearch -h ADServer1 -p 389 -b "DC=mycompany,DC=lan" -x -D "CN=LDAP Access,CN=Users,DC=mycompany,DC=lan" -w users-password -v
# ldapsearch -h ADServer2 -p 389 -b "DC=mycompany,DC=lan" -x -D "CN=Vertical Response,OU=Marketing,OU=MyCompany Users,DC=mycompany,DC=lan" -w userspassword -v

Host Based Authentication(hba) on PostGres

/etc/postgresql/8.3/main/
# sudo cp pg_hba.conf pg_hba.conf.safe
# IPv4 local connections:
# Prevent all local access even by admins and root users
# host    all         all         127.0.0.1/32          md5
# Remote TCP/IP connection
host    all         all         10.5.5.0/16          ldap "ldap://ADServer1:389/OU=Mycompany Users,DC=mycompany,DC=lan;MYCOMPANY\"
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 stop
 * Stopping PostgreSQL 8.3 database server
   ...done.
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 start
 * Starting PostgreSQL 8.3 database server
   ...done.
root@myserver:/etc/postgresql/8.3/main#
TEST
root@myserver:/etc/postgresql-common# psql -h localhost -p 5432 -d projectdb -U user_a -W
Password for user user_a: 
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)

projectdb=> \q
root@myserver:/etc/postgresql-common# psql -h localhost -p 5432 -d projectdb -U user_b -W
Password for user user_b: 
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)

projectdb=# \q
root@myserver:/etc/postgresql-common#

Local Authentication for Admins + LDAP Authentication for Remote Clients

# IPv4 local connections:
# Permit local conenctions for admins, for example: admin, root and postgres accounts(DBAs and superusers)
host    all         all         127.0.0.1/32          md5
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD

# "local" is for Unix domain socket connections only
local   all         all                               ident sameuser
# IPv4 local connections:
host    all         all         127.0.0.1/32          md5

# IPv6 local connections:
host    all         all         ::1/128               md5

# Remote TCP/IP connection
# Force all remote connections to use LDAP authentication against SFDC1
host    all         all         10.5.5.0/16          ldap "ldap://ADServer1:389/OU=MyCompany Users,DC=mycompany,DC=lan;MYCOMPANY\"
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 stop
 * Stopping PostgreSQL 8.3 database server
   ...done.
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 start
 * Starting PostgreSQL 8.3 database server
   ...done.

Local Authentication for Admins + LDAP Authentication for Active Dir connections(REMOTE+LOCAL)

# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD

# "local" is for Unix domain socket connections only
local   all         all                               ident sameuser
# IPv4 local connections:
# Let admins and local superuser accounts connect to the DB using password
host    all         all         127.0.0.1/32         trust sameuser

# IPv6 local connections:
host    all         all         ::1/128               md5

# Remote TCP/IP connection
# Allow local connection exceptions .... by superusers(postgres,root,admin)
# Force all remote connections to use LDAP authentication against SFDC1
host    all     postgres,root,admin     10.5.5.0/16     password
host    all         all         10.5.5.0/16          ldap "ldap://ADServer1:389/OU=MyCompany Users,DC=mycompany,DC=lan;MYCOMPANY\"
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 stop
 * Stopping PostgreSQL 8.3 database server
   ...done.
root@myserver:/etc/postgresql/8.3/main# /etc/init.d/postgresql-8.3 start
 * Starting PostgreSQL 8.3 database server
   ...done.

PostGres Versions

Server

user_b@dbproject:~$ sudo -u postgres psql postgres
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

postgres=# select version();
                                             version                                             
-------------------------------------------------------------------------------------------------
 PostgreSQL 8.3.7 on x86_64-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
(1 row)

postgres=# \q
user_b@dbproject:~$ 

Client

user_b@dbproject:~$ psql --version
psql (PostgreSQL) 8.3.7
contains support for command-line editing
user_b@dbproject:~$ 

PostGresSQL FAQs

locate psql
Personal tools
Namespaces
Variants
Actions
Richard Esmonde.com
Wiki Navigation
Toolbox