Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- class DatabaseConnector{
- private static final String URL = "jdbc:mysql://localhost:3306/";
- private static final String DB = "en";
- private static final String DRIVER = "com.mysql.jdbc.Driver";
- private Connection con = null;
- private String username = "";
- private String password = "";
- public DatabaseConnector(String u, String p){
- username = u;
- password = p;
- try{
- Class.forName(DRIVER);
- con = DriverManager.getConnection(URL+DB, username, password);
- System.out.println("Successfully connected to the database as " + username);
- }
- catch(SQLException sqe){
- System.err.println("Unable to connect: Incorrect Username or Password");
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
- public void modify(String table, String query) throws SQLException{
- Statement stmt = con.createStatement();
- stmt.executeUpdate(query);
- System.out.println("Record successfully added");
- }
- public ResultSet query(String query) throws SQLException{
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(query);
- System.out.println("Query successfully executed");
- return rs;
- }
- public String[] toArray(ResultSet rs, int col) throws SQLException{
- int size = getSize(rs);
- String[] results = new String[size];
- for(int i=0; i<size; i++){
- results[i]=rs.getString(col);
- rs.next();
- }
- return results;
- }
- public String[] toArray(ResultSet rs, String col) throws SQLException{
- int size = getSize(rs);
- String[] results = new String[size];
- for(int i=0; i<size; i++){
- results[i]=rs.getString(col);
- rs.next();
- }
- return results;
- }
- private int getSize(ResultSet rs) throws SQLException{
- rs.last();
- int size = rs.getRow();
- rs.first();
- return size;
- }
- public static void main(String[] args){
- try{
- DatabaseConnector dc = new DatabaseConnector("root","root");
- ResultSet rs = dc.query("SELECT * from BARTENDER");
- String[] results = dc.toArray(rs,"sex");
- for(int i =0; i<results.length; i++){
- System.out.println(results[i]);
- }
- }
- catch(Exception e){
- e.getStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement