Created
December 2, 2013 08:20
-
-
Save VuokkoVuorinnen/7746582 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Helpers; | |
import java.io.IOException; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
public final class Database { | |
public static Database instance = new Database(); | |
private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver"; | |
private static final String url = "jdbc:derby://localhost:1527/dn_irc"; | |
private static final String username = "dn_irc"; | |
private static final String password = "dn_irc"; | |
private Database() { | |
try { | |
Class.forName(driver); | |
} catch (ClassNotFoundException ex) { | |
System.err.println(ex.getMessage()); | |
} | |
} | |
/** | |
* Open a connection with this database | |
*/ | |
private Connection getConnection() throws SQLException, IOException { | |
return DriverManager.getConnection(url, username, password); | |
} | |
public static boolean isRegistered(String username, String password) { | |
Connection con = null; | |
try { | |
con = instance.getConnection(); | |
Statement s = con.createStatement(); | |
s.executeQuery("SELECT COUNT(*) FROM users WHERE username LIKE '" + username + "' AND password LIKE '" + password + "'"); | |
s.getResultSet().next(); | |
return s.getResultSet().getInt(1) == 1; | |
} catch (IOException | SQLException ex) { | |
System.err.println(ex.getMessage()); | |
return false; | |
} finally { | |
try { | |
con.close(); | |
} catch (SQLException ex) { | |
System.err.println(ex.getMessage()); | |
} | |
} | |
} | |
public static void logMessage(String username, String message) { | |
Connection con = null; | |
try { | |
con = instance.getConnection(); | |
Statement s = con.createStatement(); | |
s.executeUpdate("INSERT INTO LOG (Username, Message) VALUES ('" + username + "','" + message + "')"); | |
} catch (IOException | SQLException ex) { | |
System.err.println(ex.getMessage()); | |
} finally { | |
try { | |
con.close(); | |
} catch (SQLException ex) { | |
System.err.println(ex.getMessage()); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
String username = "Vuokko"; | |
String password = "letmein"; | |
String message = "Lorem ipsum dolor sit amet!"; | |
System.out.println(Database.isRegistered(username, password)); | |
Database.logMessage(username, message); | |
System.out.println("Done!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment