Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Thursday, May 4, 2017

Open Source: Dockerfile for MariaDB on CentOS

Previously I need to have a version of mariadb running on Windows without any installation, during the process i developed two solutions:
  • a standalone mariadb in java using embedded mariadbs server 
  • a docker image which that automates the configuration of mariadb on centos container
The dockerfile and associated files which build and configure mariadb for centos is now released as an open-source project in github:


The features and usage of this docker image is described below:



Docker Project logo Mariadb Project logo

Features

  • The docker image is built from centos/systemd
  • Allow user to create a database in the mariadb if the database is not created when docker container is started
  • Allow user to configure the password for the 'root' account of mariadb
  • Allow user to user to ssh into the container to start or stop the mariadb if needed
  • Allow user to configure the mariadb such as default encoding, maximum connections, max packat allowed

Usage

Git clone the project to your local computer:
git clone https://github.com/chen0040/dockerfile-centos-mariadb.git

Build the mariadb docker image

Run the following command from the root folder of the project to build your own docker image:
docker build -t xschen/mariadb .
You can optionally save the image by running the following command:
docker save -o xschen-mariadb.img xschen/mariadb

Create and start the docker container

docker run -it --name=xschen-mariadb -u 0  -d -p 3306:3306 xschen/mariadb
Now you should be able to connect to the mariadb from your local computer at the port 3306,
an example of the data source url will be:
jdbc:mysql://127.0.0.1:3306/my_database?useSSL=false&useUnicode=yes&characterEncoding=UTF-8
Note that 127.0.0.1 may need to be replaced with the ip of your docker machine VM (depends how you set up your docker machine)

Start and stop the mariadb in the container

To start or stop the mariadb in the container, make sure that the container is running, then run the following command from your local computer:
docker exec -it xschen-mariadb /bin/bash
Once in the container, run the following command to start or stop the mariadb:
$ cd /home/xschen
$ sudo ./start.sh
$ cd /home/xschen
$ sudo ./stop.sh

Wednesday, March 30, 2016

Install and Run MySQL on CentOS

To install mysql run the following command:

```bash
`yum install mysql
`rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
`yum -y install mysql-community-server

Run the following command to start mysql:

`bash
`service mysql start

Run the following command to enable mysql on VM restart:

`bash
`chkconfig --levels 235 mysql on

Run the following command to access mysql

```bash
`mysql -u root

To configure myql for security run the following command:

```bash
`/usr/bin/mysql_secure_installation
Set root password? [Y/n] Y
Remove anonymous users? [Y/n] Y
Disallow root login remotely? [Y/n] n
Remove test database and access to it? [Y/n] Y
Reload privilege tables now? [Y/n] Y

Run the following command to restart mysql

```bash
`systemctl restart mysql.service

After the above steps "mysql -u root" will no longer be able to access mysql, Use the following command instead:

```bash
`mysql -u root -p mysql

To allow java applications to access mysql from another computer, run the following query and then restart mysql:

> update user set host="%" where user="root" and host='localhost';

Furthermore, ports may be blocked by firewalld running in the VM that runs the myql, which will block access by java application from another computer, this can be
resolved by stopping and disabling firewalld:

```bash
`systemctl stop firewalld.service
`systemctl disable firewalld.service

Wednesday, June 17, 2015

Deploy spring mvc application in cloud

After login to the cloud computing instance, run either the "uname -a" or "cat /etc/redhat-release" to discuss the linux os version of the instance.

Follows the following link to install and run tomcat server:
http://tecadmin.net/install-tomcat-8-on-centos-rhel-and-ubuntu


If your spring mvc uses MySQL for database backend, follows the following link to install and run mysql:

http://www.rackspace.com/knowledge_center/article/installing-mysql-server-on-centos
(for centos 7): https://devops.profitbricks.com/tutorials/install-mysql-on-centos-7/

Once you have the environment setup, follow the link below to deploy your Spring MVC framework into the cloud computing instance:

link: http://www.mkyong.com/maven/how-to-deploy-maven-based-war-file-to-tomcat/


Monday, November 24, 2014

Integration of Kafka-Trident-MySQL

This post shows a most basic example in which user can integrate Kafka, Trident (on top of Storm) and MySQL. The example uses a Kafka producer which randomly produce messages to Kafka brokers (a random list of country names), a TransactionalTridentKafkaSpout is used pull data from Kafka messaging system and emits the tuples (containing the field "str" which is the country names from the Kafka producer) to a Trident operation that serialize the received messages into the mysql database.

Some ZooKeeper and Kafka settings need to be explained before we proceed. the source codes developed here assumes that the ZooKeepers runs on the following nodes:

192.168.2.2:2181
192.168.2.4:2181

and also assumes that the Kafka brokers runs at the following hostname:port:

192.168.2.2:9092
192.168.2.4:9092

The Kafka producer can be downloaded from the following link:

https://dl.dropboxusercontent.com/u/113201788/storm/kakfa-producer-for-trident.tar.gz

Basically the Kafka producer emits a random list of country names as messages sent to the Kafka brokers. The tutorial on how to implement Kafka producer can be found at:

Next we need to create Maven project (e.g. with groupId="com.memeanalytics" and artifactId="kafka-trident-consumer") which will consumes the Kafka message in a Trident topology and serialize it to mysql database. The source codes of the project can be downloaded from:

https://dl.dropboxusercontent.com/u/113201788/storm/kafka-trident-consumer.zip

Below we will explain how to prepare the pom.xml file, implement the storm operation for mysql serialization, as well as configuration of Trident topology which can consume messages from Kafka brokers.

Prepare pom.xml

In the pom.xml, first add in the clojars repository in the repositories section:

  <repositories>
  <repository>
  <id>clojars</id>
  <url>http://clojars.org/repo</url>
  </repository>
  </repositories>

Next add in the storm-kafka-0.8-plus dependency in the dependencies section (for TransactionalTridentKafkaSpout):

<dependency>
  <groupId>net.wurstmeister.storm</groupId>
  <artifactId>storm-kafka-0.8-plus</artifactId>
  <version>0.4.0</version>
</dependency>

Next add in the storm-core dependency in the dependencies section (for storm):

<dependency>
  <groupId>storm</groupId>
  <artifactId>storm-core</artifactId>
  <version>0.9.0.1</version>
</dependency>

Next add in the mysql-connector-java dependency in the dependencies section (for mysql):

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.6</version>
</dependency>

Next add in the maven-assembly-plugin in the build/plugins section (for packaging the Maven project as jar for submitting to Storm cluster):

<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass></mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>

Next add in the exec-maven-plugin in the build/plugins section (for executing the Maven project):

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>

<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>

<configuration>
<includeProjectDependencies>true</includeProjectDependencies>
<includePluginDependencies>false</includePluginDependencies>
<executable>java</executable>
<classpathScope>compile</classpathScope>
<mainClass>com.memeanalytics.kafka_trident_consumer.App</mainClass>
</configuration>

</plugin>

This completes the pom.xml configuration. Next we will implements the Trident operation which serializes the TridentTuple data into mysql database.

Trident operation for mysql serialization

The Trident operation which serializes the TridentTuple data is a BaseFilter object from Trident that has the following implementation:

package com.memeanalytics.kafka_trident_consumer;

import java.util.Map;

import storm.trident.operation.BaseFilter;
import storm.trident.operation.TridentOperationContext;
import storm.trident.tuple.TridentTuple;

public class TridentUtils {
 public static class MySqlPersist extends BaseFilter{

  private static final long serialVersionUID = 1L;

  private MySqlDump mysqlSerializer=null;
  
  public boolean isKeep(TridentTuple tuple) {
   String country=tuple.getString(0);
   mysqlSerializer.store(country);
   System.out.println("Country: "+country);
   return true;
  }
  
  @Override
     public void prepare(Map conf, TridentOperationContext context) {
   mysqlSerializer=new MySqlDump("localhost","mylog", "root", "[username]");
     }

     @Override
     public void cleanup() {
      mysqlSerializer.close();
     }
  
 }
}

In the above implementation, the mysqlSerializer member variable is responsible for actually storing the data in mysql database. it opens the mysql connection (in its constructor) in prepare() method and closes the mysql connection in cleanup() method. the data serialization happens in the execute() method. Below is the implementation of the class of the variable:

package com.memeanalytics.kafka_trident_consumer;

import java.sql.Connection;
import java.sql.SQLException;

import java.sql.PreparedStatement;

public class MySqlDump {
 private String ip;
 private String database;
 private String username;
 private String password;
 private Connection conn;
 
 public MySqlDump(String ip, String database, String username, String password)
 {
  this.ip = ip;
  this.database=database;
  this.username=username;
  this.password=password;
  conn=MySqlConnectionGenerator.open(ip, database, username, password);
 }
 
 public void store(String dataitem)
 {
  if(conn==null) return;
  
  PreparedStatement statement = null;
  try{
   statement = conn.prepareStatement("insert into mylogtable (id, dataitem) values (default, ?)");
   statement.setString(1, dataitem);
   statement.executeUpdate();
  }catch(Exception ex)
  {
   ex.printStackTrace();
  }finally
  {
   if(statement != null)
   {
    try {
     statement.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 
 public void close()
 {
  if(conn==null) return;
  try {
   conn.close();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}
package com.memeanalytics.kafka_trident_consumer;

import java.sql.Connection;
import java.sql.DriverManager;

public class MySqlConnectionGenerator {
 public static Connection open(String ip, String database, String username, String password)
 {
  Connection conn = null;
  try{
   Class.forName("com.mysql.jdbc.Driver");
   conn=DriverManager.getConnection("jdbc:mysql://"+ip+"/"+database+"?user="+username+"&password="+password);
  }catch(Exception ex)
  {
   ex.printStackTrace();
  }
  
  return conn;
 }
}

Trident topology implementation

Once this is completed. we are ready to implement the Trident topology which consumes data from Kafka and saves it to mysql. this is implemented in the main class:

package com.memeanalytics.kafka_trident_consumer;

import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.spout.SchemeAsMultiScheme;
import backtype.storm.tuple.Fields;
import storm.kafka.SpoutConfig;
import storm.kafka.StringScheme;
import storm.kafka.ZkHosts;
import storm.kafka.trident.TransactionalTridentKafkaSpout;
import storm.kafka.trident.TridentKafkaConfig;
import storm.trident.TridentTopology;

public class App 
{
    public static void main( String[] args ) throws AlreadyAliveException, InvalidTopologyException
    {
        ZkHosts zkHosts=new ZkHosts("192.168.2.4:2181");
        
        String topic="country-topic";
        String consumer_group_id="storm";
        
        TridentKafkaConfig kafkaConfig=new TridentKafkaConfig(zkHosts, topic, consumer_group_id);
        
        kafkaConfig.scheme=new SchemeAsMultiScheme(new StringScheme());
        kafkaConfig.forceFromStart=true;
        
        TransactionalTridentKafkaSpout spout=new TransactionalTridentKafkaSpout(kafkaConfig);
        
        TridentTopology topology=new TridentTopology();
        
        topology.newStream("spout", spout).shuffle().each(new Fields("str"), new TridentUtils.MySqlPersist());
        
        LocalCluster cluster=new LocalCluster();
        
        Config config=new Config();
        
        cluster.submitTopology("KafkaTridentMysqlDemo", config, topology.build());
        
        try{
         Thread.sleep(10000);
        }catch(InterruptedException ex)
        {
         ex.printStackTrace();
        }
        
        cluster.killTopology("KafkaTridentMysqlDemo");
        cluster.shutdown();
    }
}

For demo purpose, its uses LocalCluster to submit and run the Trident topology and does not implement a DRPCStream which can be used to queried result. The main change is the TractionalTridentKafkaSpout which takes in a TridentKafkaConfig object as parameter in its constructor. The TransactionalTridentKafkaSpout emits tuples which is serialized by the TridentUtil.MySqlPersist that is the mysql serialization Trident operation.

Once done, we can compile and exec the Maven project by navigating to its root folder and run the following command:

> mvn compile exec:java

Integration of Kafka-Storm-MySQL

This post will discuss how to create a minimum basic storm topology which integrate Kafka, Storm and MySQL. The scenerios is: a Kafka producer will push some dummy data to the Kafka brokers, and a KafkaSpout (with consumer group id = "id7" and zookeeper = "192.168.2.4:2181") from storm cluster consumes data from the Kafka brokers. The KafkaSpout will then emits Kafka messages as tuples to a BaseBasicBolt which will then persists the data to the MySQL server.

The post assumes user already have a zookeeper cluster set up on two hostname:port:

192.168.2.2:2181
192.168.2.4:2181

The post also assumes that the Kafka brokers runs at the following hostname:port:

192.168.2.2:9092
192.168.2.4:9092

Details of how to set up ZooKeeper and Kafka cluster can be found at the following links:

http://czcodezone.blogspot.sg/2014/11/setup-zookeeper-in-cluster.html
http://czcodezone.blogspot.sg/2014/11/setup-kafka-in-cluster.html

The Kafka producer source codes can be downloaded from the link: https://dl.dropboxusercontent.com/u/113201788/kafka-producer.zip. The details about how to implement a simple Kafka producer in java can be found at this link: http://czcodezone.blogspot.sg/2014/11/write-and-test-simple-kafka-producer.html).

To create the Storm topology which consumes messages from Kafka and persists them to MySQL database, create a Maven project (e.g. with groupId="com.memeanalytics" and artifactId="storm-kafka-mysql"). The complete source code of the project can be downloaded from the following link:

https://dl.dropboxusercontent.com/u/113201788/storm/storm-kafka-mysql.tar.gz

Maven setup: pom.xml

We will start by explaining setup in the pom.xml file. Firstly, we need to put in the clojars in the repositories:

  <repositories>
  <repository>
  <id>clojars</id>
  <url>http://clojars.org/repo</url>
  </repository>
  </repositories>

Next we add the mysql dependency into the dependencies section:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

Next we add the storm-kafka-0.8-plus dependency into the dependencies section (for KafkaSpout which consumers Kafka messages in Storm):

<dependency>
<groupId>net.wurstmeister.storm</groupId>
<artifactId>storm-kafka-0.8-plus</artifactId>
<version>0.4.0</version>
</dependency>

Next we add the storm-core dependency into the dependencies section (for Storm):

<dependency>
<groupId>storm</groupId>
<artifactId>storm-core</artifactId>
<version>0.9.0.1</version>
<scope>provided</scope>
</dependency>

Next we add the exec-maven-plugin into the build/plugins section (for compile and execute java project):

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<includeProjectDependencies>true</includeProjectDependencies>
<includePluginDependencies>false</includePluginDependencies>
<executable>java</executable>
<classpathScope>compile</classpathScope>
<mainClass>${main.class}</mainClass>
</configuration>
</plugin>

Next we add the maven-assembly-plugin into the build/plugins section (for packaging the java project as jar to submit to the Storm cluster):

<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descrptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass></mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>

MySQL Connection and Management Classes

Next we will create a class that manages MySQL connection, the source codes of which are show below:

package com.memeanalytics.storm_kafka_mysql;

import java.sql.Connection;
import java.sql.DriverManager;


public class MySqlConnection {
 private String ip;
 private String database;
 private String username;
 private String password;
 private Connection conn;
 
 public MySqlConnection(String ip, String database, String username, String password)
 {
  this.ip=ip;
  this.database=database;
  this.username=username;
  this.password=password;
 }
 
 public Connection getConnection()
 {
  return conn;
 }
 
 public boolean open()
 {
  boolean successful=true;
  try{
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+database+"?"+"user="+username+"&password="+password);
  }catch(Exception ex)
  {
   successful=false;
   ex.printStackTrace();
  }
  return successful;
 }
 
 public boolean close()
 {
  if(conn==null)
  {
   return false;
  }
  
  boolean successful=true;
  try{
   conn.close();
  }catch(Exception ex)
  {
   successful=false;
   ex.printStackTrace();
  }
  
  return successful;
 }
}

As illustrated above, the MySqlConnection manages the opening and closing of the connection.

Next we will create a class which saves the tuples emitted from the KafkaSpout into the MySQL server.

package com.memeanalytics.storm_kafka_mysql;

import java.sql.PreparedStatement;

import backtype.storm.tuple.Tuple;

public class MySqlDump {
 private MySqlConnection conn;
 
 public MySqlDump(String ip, String database, String username, String password)
 {
  conn = new MySqlConnection(ip, database, username, password);
  conn.open();
 }
 
 public void persist(Tuple tuple)
 {
  PreparedStatement statement=null;
  try{
   statement = conn.getConnection().prepareStatement("insert into mylogtable (id, dataitem) values (default, ?)");
   statement.setString(1, tuple.getString(0));
   
   statement.executeUpdate();
  }catch(Exception ex)
  {
   ex.printStackTrace();
  }finally
  {
   if(statement != null)
   {
    try{
     statement.close();
    }catch(Exception ex)
    {
     ex.printStackTrace();
    }
   }
  }
 }
 
 public void close()
 {
  conn.close();
 }
}

The above classes opens the mysql connection in its constructor, and will saves the tuple via its persist() method, it also has a close() method which can be invoked to close the mysql connection.

Before we proceed further, we need to create the necessary database and datatable in mysql so that data can be inserted into. For demo purpose, we create a very basic datatable named "mylogtable" in a database named "mylog". To do this, access the mysql server by running the command:

> mysql -u [username] -p

Once logged into the mysql, run the following mysql queries to create the mylogtable:

> create database mylog;
> user mylog;
> create table mylogtable( id INT NOT NULL AUTO_INCREMENT, dataitem VARCHAR(255) NOT NULL, PRIMARY KEY(id));

Storm Bolt to persists data

Once this is done. We are ready to create a Storm bolt which route the received tuple from KafkaSpout to the MySqlDump which saves it to the database:

package com.memeanalytics.storm_kafka_mysql;

import java.util.Map;

import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Tuple;

public class MySqlDumpBolt extends BaseBasicBolt{

 private static final long serialVersionUID = 1L;
 private MySqlDump mySqlDump;

 @Override
 public void prepare(Map stormConf, TopologyContext context)
 {
  mySqlDump=new MySqlDump("localhost", "mylog","root","[username]");
 }
 
 public void execute(Tuple input, BasicOutputCollector collector) {
  // TODO Auto-generated method stub
  mySqlDump.persist(input);
  //System.out.println(input);
 }

 public void declareOutputFields(OutputFieldsDeclarer declarer) {
  // TODO Auto-generated method stub
  
 }
 
 @Override
    public void cleanup() {
  mySqlDump.close();
    }  

}

As can be seen above, the bolt opens the mysql database connection in its prepare() method and close the mysql database connection in its cleanup() method. it also persists the tuple received into mysql datatable in its execute() method.

Submit Topology in main()

Now we can implement the main() method to submit a topology. For simplicity, we only uses local cluster:

package com.memeanalytics.storm_kafka_mysql;

import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.spout.SchemeAsMultiScheme;
import backtype.storm.topology.TopologyBuilder;
import storm.kafka.KafkaSpout;
import storm.kafka.SpoutConfig;
import storm.kafka.StringScheme;
import storm.kafka.ZkHosts;

public class App 
{
    public static void main( String[] args ) throws AlreadyAliveException, InvalidTopologyException
    {
        ZkHosts zkHosts=new ZkHosts("192.168.2.4:2181");
        
        String topic="test-topic";
        String consumer_group_id="id7";
        
        SpoutConfig kafkaConfig=new SpoutConfig(zkHosts, topic, "", consumer_group_id);
        
        kafkaConfig.forceFromStart=true;
        kafkaConfig.scheme=new SchemeAsMultiScheme(new StringScheme());
        
        KafkaSpout kafkaSpout=new KafkaSpout(kafkaConfig);
        
        TopologyBuilder builder=new TopologyBuilder();
        builder.setSpout("KafkaSpout", kafkaSpout);
        builder.setBolt("MySqlBolt", new MySqlDumpBolt()).globalGrouping("KafkaSpout");
        
        LocalCluster cluster=new LocalCluster();
        
        Config config=new Config();
        
        cluster.submitTopology("MySqlDemoTopology", config, builder.createTopology());
        
        try{
         Thread.sleep(10000);
        }catch(InterruptedException ex)
        {
         ex.printStackTrace();
        }
        
        cluster.killTopology("MySqlDemoTopology");
        cluster.shutdown();
    }
}

Execute Maven project

Now navigate to the project root folder and run the following command:

> mvn exec:java -Dmain.class=com.memeanalytics.storm_kafka_mysql.App

Note that if you change the ${main.class} to com.memeanalytics.storm_kafka_mysql.App, that you don't need to add the -Dmain.class arguments in the above command.

Setup and run MySQL on Ubuntu 14.04 LTS

Suppose you want to install and run MySQL on Ubuntu, run the following commands to install the MySQL in the terminal:

> sudo apt-get install mysql-server
> sudo apt-get install mysql-client

During the installation of the mysql-server, the user will prompted to enter the password for the root user account. After the installation is completed, the user can run the following command to find out whether mysql-server is running on the computer:

> sudo netstat -tap | grep mysql

To start, stop or restart mysql, run one of the following commands:

> sudo /etc/init.d/mysql start
> sudo /etc/init.d/mysql stop
> sudo /etc/init.d/mysql restart

To log into mysql, run the following command

> sudo mysql -u [username] -p

Enter the password in the prompt and press ENTER. For example, to log into the root user account:

> mysql -u root -p

After logging into mysql, first select the database by running the following sql command (which select the database "mysql" which is the default):

> use mysql;

To list the tables in the "mysql" database, run the following sql command:

> show tables;

Now suppose we want to take a look at what is inside the "user" datatable. Run the following sql command:

> select * from user;

To create and select a new database, e.g., "mylog", run the following sql command:

> create database mylog;
> use mylog;

To create a datatable, e.g., "mylogtable", in the database "mylog", run the following sql commands:

> use mylog;
> create table mylogtable(
id INT NOT NULL AUTO_INCREMENT,
country VARCHAR(255) NULL);

To exit mysql, run the following sql command:

> quit;

Wednesday, October 9, 2013

SQL Query to get the database size in MySQL

The following query will returns the the database name and corresponding database size in MySQL

SELECT table_schema "Data Base Name", sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB" 
FROM information_schema.TABLES GROUP BY table_schema ; 

Import large SQL File into MySQL Server in XAMP / WAMP

To import a large SQL file into MySQL Server in WAMP, copy the SQL file into "C:\wamp\bin\mysql\mysql5.5.24\bin", and navigate to the "C:\wamp\bin\mysql\mysql5.5.24\bin" in the command line window, then in the command line enter:

mysql -u [username] -p [DatabaseName] < [SQLFileName]

for example, is the [username] is root and [DatabaseName] is mixertruck, and the [SQLFilename] is mixertruck.sql, then the command line is 

mysql -u root -p mixertruck < mixertruck.sql

if the mysql is on a remote server, then use the following command line:

mysql -u [username] -h [HostName] -p [DatabaseName] < [SQLFileName]

Tuesday, January 11, 2011

php date in mysql

To create a datetime field in mysql database, create a DATETIME fieldtype, e.g.
the sql "CREATE TABLE [tablename] id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , last_updated DATETIME NOT NULL" will create a autoincrement primary key "id" and a DATETIME field "last_updated"

To insert a datetime into the above table from php, the php code looks like:
"INSERT INTO [tablename] (last_updated) value (\"".date("Y-m-d H:i:s")."\");" where date("Y-m-d H:i:s") is the php statement that gets the current date format.