How do I create a connection to database?
Category: java.sql, viewed: 17946 time(s).
An example for obtaining a connection to MySQL database. For connecting to other database all you have to do is change the url to match to url format for a particular database and of course you have to register a correct JDBC driver of the database you are using.
package org.kodejava.sample.java.sql;
import java.sql.DriverManager;
import java.sql.Connection;
public class ConnectionSample
{
// Below is the format of jdbc url for MySql database.
public static final String URL =
"jdbc:mysql://localhost/testdb";
// The username for connecting to the database
public static final String USERNAME = "root";
// The password for connecting to the database
public static final String PASSWORD = "";
public static void main(String[] args) throws Exception
{
Connection connection = null;
try
{
// Register a database jdbc driver to be used by
// our program. In this example I choose a MySQL
// driver.
Class.forName("com.mysql.jdbc.Driver");
// Get the connection object from the driver manager
// by passing the url of our database, username and
// the password.
connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
// Do what ever you want to do with the connection
// object, such as reading some records from database,
// updating or deleting a row. But don't for get the
// close the connection right after you've finished
// using it.
} finally
{
if (connection != null)
{
connection.close();
}
}
}
}
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!