Import the jar package first
Code:
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
public class Firstjdbc {
public static void Main (string[] args) throws ClassNotFoundException, SQLException {
1) Register Load Driver
Class.forName ("Com.mysql.jdbc.Driver");
Drivermanager.registerdriver (New Com.mysql.jdbc.Driver ());
2) Get Connected
String url = "Jdbc:mysql://localhost:3307/mydb";//mydb is the name of the database
String user = "root"; Login name of the database
String password = "123456"; Login Password for database
Connection conn = drivermanager.getconnection (URL, user, password);
3) Create statement object
Statement st = Conn.createstatement ();
4) Execute SQL to get results
String sql = "SELECT * from EMP"; EMP is the name of the table to query
ResultSet rs= st.executequery (SQL);
5) Processing Results
while (Rs.next ()) {
System.out.print (Rs.getobject (1) + "\ T");
System.out.print (Rs.getobject (2) + "\ T");
System.out.print (Rs.getobject (3) + "\ T");
System.out.print (Rs.getobject (4) + "\ T");
System.out.print (Rs.getobject (5) + "\ T");
System.out.print (Rs.getobject (6) + "\ T"); Total output of field name information to display
}
6) Close Resources
Rs.close ();
St.close ();
Conn.close ();
}
}
Steps for JDBC Connection database (query)