×
Home About Us Products Services News Free Scripts Contact
news php scripts and software

Databases example - How to connect and execute SELECT statements in MySQL with JAVA?


Databases - How to connect and execute SELECT statements in MySQL with JAVA?

import java.sql.*;

public class Select
{

public static void main (String[ ] args)
{
	Connection conn = null;
	String url = "jdbc:mysql://localhost/";
	String userName = "username1";
	String password = "password1";

	try
	{
		Class.forName ("com.mysql.jdbc.Driver").newInstance ( );
		conn = DriverManager.getConnection (url, userName, password);
		// System.out.println ("Connected");

		Statement s = conn.createStatement ( );
		s.executeQuery ("SELECT pkey,name,exam,score FROM test.exams");
		ResultSet rs = s.getResultSet ( );
		int count = 0;
		while (rs.next ( )) // loop through rows of result set
		{
			int pkey = rs.getInt (1);
			String name = rs.getString(2);
			int exam = rs.getInt(3);
			int score = rs.getInt(4);
			++count;
			System.out.println (count + ",inum: " + pkey + ",name: " +
			name + ",exam: " + exam + ",score: " + score );
		}
		rs.close ( ); // close result set
		s.close ( ); // close statement
		System.out.println (count + " rows were returned");

	}
	catch (Exception e)
	{
		System.err.println ("Cannot connect to server"+e);
	}
	finally
	{
		if (conn != null)
		{
			try
			{
				conn.close ( );
				// System.out.println ("Disconnected"); /* for debugging */
			}
			catch (Exception e) { /* ignore close errors */ }
		}
	}
	}

}

Category: Databases

 
<< Go back