MySQL version
If the following program runs OK, then we have everything
installed OK. We check the version of the MySQL server.
package zetcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Version {
public static void main(String[] args) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "testuser";
String password = "test623";
try {
con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet result = st.executeQuery("SELECT VERSION()");
if (result.next()) {
System.out.println(result.getString(1));
}
con.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
We connect to the database and get some info about the MySQL server.
String url = "jdbc:mysql://localhost:3306/testdb";
This is the connection url for the MySQL database. Each driver
has a different syntax for the url. In our case, we provide a
host, a port and a database name.
con = DriverManager.getConnection(url, user, password);
We establish a connection to the database, using the connection url,
user name and password.
Statement st = con.createStatement();
The createStatement() method of the connection
object creates a Statement object for sending SQL statements to the database.
ResultSet result = st.executeQuery("SELECT VERSION()");
The createStatement() method of the connection
object executes the given SQL statement, which returns a single ResultSet object.
The ResultSet is a table of data returned by a specific SQL statement.
if (result.next()) {
System.out.println(result.getString(1));
}
A ResultSet object maintains a cursor pointing to its current row of data.
Initially the cursor is positioned before the first row. The next()
method moves the cursor to the next row. If there are no rows left, the method
returns false. The getString() method retrieves the value
of a specified column. The first column has index 1.
con.close();
The connection to the database is closed.
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
In case of an exception, we print an error message to the
terminal.
$ java -cp .:lib/mysql-connector-java-5.1.13-bin.jar zetcode/Version
5.1.41-3ubuntu12.6
This is the output of the program on my system.
information come from : http://zetcode.com/databases/mysqljavatutorial/
0 意見:
張貼留言