Connecting to the MySql database in java
Step 1:
Two ways to load the jar file:
- paste the mysqlconnector.jar file in jre/lib/ext folder
- set classpath
1) paste the mysqlconnector.jar file in JRE/lib/ext folder:
|
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here. |
2) set classpath:
|
There are two ways to set the classpath:
set classpath= C:foldermysql-connector.jar;.;
|
Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:foldermysql-connector.jar;.;
Step 2:
Create a table in the mysql database, but before creating table, we need to create database first.
Open MySql prompt and type following:
- create database sydb;
- use sydb;
- create table student(rollno int(5),name varchar(40),marks int(3));
Program which connects to MySql database with database name=sydb id=root and password=pass123:
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/sydb”,”root”,”pass123″);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“select * from student”);
while(rs.next())
System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Note: If you are doing in Netbeans then download mysql-connector.jar and add to to project library.
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data types used in a database.