MySQL connection from Eclipse

MySQL Configuration using mysql-connector.jar file

After configuration of mysql-connector.jar file, you can try this code.

In our script we used following values.

Database Name = my_tutorial
User id = root
Password = my_password ( use your password )

Table name = student

Query = "SELECT * FROM student"

To get details of student table you can check here.

MySQL student table dump

We will use the above details to connect and get the data from MySQL table.
import java.sql.*;
public class mysql_connect1 {
public static void main(String[] args) throws Exception
{
	String url = "jdbc:mysql://localhost:3306/my_tutorial";
	String uname = "root";
	String pass = ""; // your password 
	String query = " SELECT * FROM STUDENT ";
	
	Class.forName("com.mysql.jdbc.Driver");
	Connection conn = DriverManager.getConnection(url,uname,pass);
	Statement st= conn.createStatement();
	ResultSet rs= st.executeQuery(query);
	
	rs.next();
	System.out.println(rs.getString("name"));
	
	rs.next();
	System.out.println(rs.getString("name"));
	
	st.close();
	conn.close();
}	
}
The output is here
John Deo
Max Ruin
This output has shown us two records ( names of two student ) .
Now we will use the ResultSet to display all the records of our student table.
import java.sql.*;
public class my_connect {
	public static void main(String args[]) 
	{  
	try{  
	Class.forName("com.mysql.jdbc.Driver");  
	Connection con=DriverManager.getConnection(  
	"jdbc:mysql://localhost:3306/my_tutorial","root","password_here");  
	Statement st=con.createStatement();  
	ResultSet rs=st.executeQuery("SELECT * FROM STUDENT"); 
		
	while(rs.next())  
	System.out.println(rs.getInt(1)+" "+rs.getString("name"));  
		
	con.close();  
	}catch(Exception e){ System.out.println(e);} 
		
	}
}
Output ( all records )
1  John Deo  Four
2  Max Ruin  Three
3  Arnold  Three
---------
--------
All records will be displayed here.

MySQL MySQL student table dump


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer