
How to access a database with JDBC via Java application?

Accessing database with JDBC through Java
JDBC Example to access Database
import java.sql.*;
public class JdbcConnect{
public static void main(String[] args) {
System.out.println("JDBC Example.");
Connection connnection = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "student";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
connnection = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
connnection .close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Connection: This is an interface in java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.
Class.forName(String driver): This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.
DriverManager: It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.
getConnection(String url, String userName, String password): This method establishes a connection to specified database url. It takes three string types of arguments like:
url: - Database url where stored or created your database
userName: - User name of MySQL
password: -Password of MySQL
con.close(): This method is used for disconnecting the connection. It frees all the resources occupied by the database.
printStackTrace(): The method is used to show error messages. If the connection is not established then exception is thrown and print the message.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.