У меня есть класс, который обрабатывает загрузку драйвера JDBC и базы данных MySQL. Он имеет объекты Connection и Statement, определенные как статические
Код: Выделить всё
/** Enables a connection to the chessleaguedb MySQL database
* @author Erdi Rowlands
*/
public class DatabaseConnection
{
private Console console; // needed for relevant method to mask console input
private Scanner keyboard; // reads user input
private String user; // MySQL user account
private String pass; // MySQL account password
private String host; // MySQL host
static Connection conn; // application needs to communicate with JDBC driver
static Statement st; // issuing commands against the connection is reqiured
/* When instantiated the JDBC driver attempts to load */
public DatabaseConnection()
{
this.loadDriver();
}
public void loadDriver()
{
try
{
Class.forName ("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println("Could not load the driver");
}
}
public void connectToDatabase()
{
try
{
this.readLogin();
// prompts user to enter login info to console
this.conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/chessleaguedb", user, pass);
System.out.println("\nSuccessfully connected to database: "
+ "'chessleaguedb'");
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
Код: Выделить всё
/** Enables the creation and population of the MySQL database 'chessleaguedb' tables
* @author Erdi Rowlands
*/
public class DatabaseTables
{
public DatabaseTables()
{
}
public void createPlayerTable()
{
try
{
DatabaseConnection.st = DatabaseConnection.conn.createStatement();
DatabaseConnection.st.executeUpdate("CREATE TABLE IF NOT EXISTS"
+ "(PlayerName VARCHAR(30)PRIMARY KEY,"
+ "DateOfBirth DATE,"
+ "FIDERating tinyint,"
+ "ClubName FOREIGN KEY fk_club(Clubname) REFERENCES club(ClubName)");
// Create Actor table
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/403 ... sign-query
Мобильная версия