JDBC——Implemente Database Connection
Interface Database
//source:
package beaver;
import java.sql.Connection;
import java.sql.SQLException;
public interface Database {
/**
* Returns a database connection.
* The database connection that is returned is always the same.
* @return A Database Connection
*/
public abstract Connection getConnection();
/**
* Returns an independent connection.
* Returns a new database connection for each call
* @return A Database Connection
*/
public abstract Connection getNewConnection() throws SQLException;
public abstract String getDatabaseName();
public abstract String getDriverName();
public abstract String getPassword();
public abstract String getUserName();
}
GenericDatabase .java
//source
package beaver;
import java.sql.*;
public class GenericDatabase implements Database {
private String driverName;
private String databaseName;
private String userName;
private String password;
private Connection con;
/**
* @throws ClassNotFoundException
* @throws SQLException
*/
public GenericDatabase(
String _driverName,
String _databaseName,
String _userName,
String _password)
throws ClassNotFoundException, SQLException {
driverName = _driverName;
databaseName = _databaseName;
userName = _userName;
password = _password;
try{
Class.forName(driverName);
con = DriverManager.getConnection(
databaseName,
userName,
password);
}catch(Exception e){
System.out.println("fail");
System.out.println(e.getMessage());
}
}
public String getDatabaseName() {
return databaseName;
}
public String getDriverName() {
return driverName;
}
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
/**
* Returns a database connection.
* The database connection that is returned is always the same.
* @return A Database Connection
*/
public Connection getConnection() {
return con;
}
/**
* Returns an independent connection.
* Returns a new database connection for each call
* This method retries until it actually gets a connection
* @return A Database Connection
*/
public Connection getNewConnection() {
Connection ncon;
while (true) {
try {
ncon =
DriverManager.getConnection(getDatabaseName(),
getUserName(),
getPassword());
return ncon;
} catch (SQLException e) {
System.err.println(e.getErrorCode() + " " + e.getMessage());
try {
// Wait for half a sec, then try again
Thread.sleep(500);
} catch (InterruptedException ie) {
// ignore
}
}
}
}
}
myDatabase .java
Connect database.If connect local database,ip is "localhost" or "127.0.0.1"
"first" is a database;"root" is usename;"11111" is password.
//source:
package beaver;
import java.sql.*;
public class myDatabase extends GenericDatabase {
public myDatabase ()
throws ClassNotFoundException, SQLException {
super("com.mysql.jdbc.Driver",
"jdbc:mysql://ip:3306/first",
"root",
"11111");
}
}

没有评论:
发表评论