To connect to the database in Java, you need to add the JDBC Jar package path to the Classpath
In Eclipse, the Java build path inside Project's properties adds a reference
A small example of a successful connection
The database is as follows
Code
Packagequery;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classQuery { Public Static voidMain (string[] args) {//driver nameString Driver = "Com.mysql.jdbc.Driver"; //URL point to the database name to access 9millionString url = "Jdbc:mysql://127.0.0.1:3306/9million"; //user name when MySQL is configuredString user = "root"; //password for MySQL configurationString Password = ""; Try { //Load DriverClass.forName (driver); //Continuous DatabaseConnection conn =drivermanager.getconnection (URL, user, password); if(!conn.isclosed ()) System.out.println ("Succeeded connecting to the database!"); //statement used to execute SQL statementsStatement Statement =conn.createstatement (); //the SQL statement to executeString sql = "SELECT * FROM TestData"; //result setResultSet rs =statement.executequery (SQL); System.out.println ("-----------------"); System.out.println (The results of the execution are as follows:); System.out.println ("-----------------"); System.out.println ("School Number" + "\ T" + "name"); System.out.println ("-----------------"); String name=NULL; while(Rs.next ()) {//Select sname This column of dataName = rs.getstring ("name"); //first, use the iso-8859-1 character set to decode name into a sequence of bytes and store the result in a new byte array. //the specified byte array is then decoded using the GB2312 character setName =NewString (Name.getbytes ("iso-8859-1"), "GB2312"); //Output ResultsSystem.out.println (rs.getstring ("id") + "\ T" +name); } rs.close (); Conn.close (); } Catch(ClassNotFoundException e) {System.out.println ("Sorry,can ' t find the driver!"); E.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } }}
A small example of Java connection to MySQL