Cross-Platform, Java

Using mysql with Java

First of all download the Connector/J. Don’t forget to add in your project a reference to mysql-connector-java-x.x.x-bin.jar file.

Let’s see the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
 
...
...
 
String url = "jdbc:mysql://127.0.0.1:3306/";
String dbName = "database_name";
String driver = "com.mysql.jdbc.Driver";
 
Class.forName(driver).newInstance();
Connection connection = DriverManager.getConnection(url+dbName,"user_name","pass_word");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select * from customers;");
 
while(rs.next()){
    System.out.println(rs.getString("LastName"));
}
 
connection.close();