Skip to content

Connecting MySQL Database from Java with JDBC

11/01/2011

First of all download the MySQL connector from
http://www.mysql.com/downloads/connector/j/

import java.sql.*;


public class ConnectDB {

	public static void main(String[] args) {
		Connection con = null;

		String username ="root";
		String password="password";
		String dbName = "myDatabaseName";

		String url = "jdbc:mysql://localhost:3306/" + dbName;
		String driver = "com.mysql.jdbc.Driver";

		String genre="classic";
		String mood ="happy";

		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, username, password);
			try {
				Statement st = con.createStatement();
				int val = st
						.executeUpdate("INSERT INTO test (genre, mood) VALUES('classic','happy')");

	} catch (SQLException s) {
				System.out.println("SQL statement is not executed!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Advertisements

From → Java Examples

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: