$cat Connect.java
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
//String query = "Select * FROM mysql.user";
String query = "Show databases";
String dbtime;
try
{
String userName = "root";
String password = "mysql";
String url = "jdbc:mysql://10.255.6.58/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
System.err.println ("Message :"+e.getMessage());
System.err.println ("Error message: " + e);
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Compile Connect.java to produce a class file Connect.class that contains executable Java code:
% javac Connect.java
Then invoke the class file as follows and it should connect to and disconnect from your MySQL server:
% java -classpath .:/path/mysql-connectorJ-5.jar Connect
Database connection established
mysql
test
userdb
Database connection terminated
http://www.kitebird.com/articles/jdbc.html
http://download.oracle.com/javase/tutorial/jdbc/basics/connecting.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
No comments:
Post a Comment