Pages Navigation Menu

Coding is much easier than you think

Connect to MySQL DB via JDBC driver

Posted by on Aug 17, 2013 in JDBC Tutorials, MySql Tutorial | 0 comments

 
Here’s an example to show you how to connect to MySQL database via a JDBC driver.
 
1. Download MySQL JDBC Driver
 
Get MySQL JDBC driver here –MySQL JDBC Driver

 2. Java JDBC connection example
 
Code snippets to use a JDBC driver to connect a MySQL database.
 
** UPDATE: Complete JDBC tutorial now available here.
 

Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", 
         "password");
conn.close();

 
See a complete example below:

File: MySqlJDBC.java
 

package com.simplecode.jdbc;

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

public class MySqlJDBC {

private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/simplecodedb";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "password";

public static void main(String[] argc) {

	System.out.println("***** MySQL JDBC Connection Testing *****");

	try 
	{
		Class.forName(DB_DRIVER);
	} 
	catch (ClassNotFoundException e) 
	{
		System.err.println("Exception : Add MySQL JDBC Driver in your classpath ");
                System.err.println(e.getMessage());
		return;
	}

	System.out.println("MySQL JDBC Driver Registered!");
	Connection connection = null;

	try 
	{
	connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
	} 
	catch (SQLException e) 
	{
		System.err.println("Connection Failed! Check console");
                System.err.println(e.getMessage());
		return;
	}

	if (connection == null) {
		System.out.println("Connection Failed!");
	} 
	else 
	{
		System.out.println("Connection established!");
	}
}
}

 

Read More

Query to properly check if a record exists

Posted by on Mar 28, 2013 in MySQL | 0 comments

 

1) select 1 from table where key = value;

2) select count(1) from table where key = value;

The first alternative should give you no result or one result, the second count should be zero or one.

Read More

How to select Last One Month Records in MySQL?

Posted by on Mar 7, 2013 in MySQL | 0 comments

 
 

SELECT * FROM <table_name> WHERE <date_field> BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW();
 
Similarly, You can select records for 2 months, 3 months etc.
 

Read More

How to select Last One Year Records in MySQL?

Posted by on Mar 7, 2013 in MySQL | 0 comments

 
SELECT * FROM <table_name> WHERE <date_field> BETWEEN DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW();

 
Similarly, You can select records for 2 years, 3 years etc.
 

Read More

How To Run A MySQL Script Using Java

Posted by on Dec 15, 2012 in Java, JDBC | 0 comments

 
In this tutorial, we shall learn about running a MySQL script file using ibatis ScriptRunner class.

Download the following libraries and add them into your classpath.

 

dwd2
Download It – ibatis      &     Mysql JDBC Driver

 

package com.simplecode.jdbc;

import java.io.Reader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.ibatis.common.jdbc.ScriptRunner;

public class ExecuteSqlScript {

private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/simplecodedb";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "password";

public static void main(String[] args) throws ClassNotFoundException,SQLException {

String sqlScriptFilePath = "C:/sql/script.sql";

// Create MySQL Connection
Class.forName(DB_DRIVER);
	
Connection connection = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD);

	try 
        {
		// Initialize object for ScriptRunner
		ScriptRunner runner = new ScriptRunner(connection, false, false);
		// Give the input file to Reader
		Reader br = new BufferedReader(new FileReader(sqlScriptFilePath));
		// Execute script
		runner.runScript(br);

	    }
         catch (Exception e) 
            {
		System.out.println("Exception Occoured" + e.getMessage());
	    }
	}
}

 
You may be also interested in
How to get Primary Key Of Inserted Record in JDBC?

 

Note

  1. You sql script should not have any select statement.
  2. sql script should have a semi colon (;) for each end of the statement.

 
dwd2
Download It – ExecuteSqlScript.java

 

References

 

Read More