List of usage examples for java.sql ResultSet next
boolean next() throws SQLException;
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getHSQLConnection(); System.out.println("Got Connection."); Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int,name varchar, PRIMARY KEY (id) );"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); ResultSet rs = null; DatabaseMetaData meta = conn.getMetaData(); // The Oracle database stores its table names as Upper-Case, // if you pass a table name in lowercase characters, it will not work. // MySQL database does not care if table name is uppercase/lowercase. ///*from w ww.j a v a 2 s .com*/ rs = meta.getPrimaryKeys(null, null, "survey"); java.util.List list = new java.util.ArrayList(); while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); System.out.println("getPrimaryKeys(): columnName=" + columnName); } st.close(); conn.close(); }
From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java
/** * Launches the interactive game server registration. * /*from ww w .j a v a 2 s . c o m*/ * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Game Server Registration"); _log.info("Please choose:"); _log.info("list - list registered game servers"); _log.info("reg - register a game server"); _log.info("rem - remove a registered game server"); _log.info("hexid - generate a legacy hexid file"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2GameServerRegistrar reg = new L2GameServerRegistrar(); String line; try { RegistrationState next = RegistrationState.INITIAL_CHOICE; while ((line = br.readLine()) != null) { line = line.trim().toLowerCase(); switch (reg.getState()) { case GAMESERVER_ID: try { int id = Integer.parseInt(line); if (id < 1 || id > 127) throw new IllegalArgumentException("ID must be in [1;127]."); reg.setId(id); reg.setState(next); } catch (RuntimeException e) { _log.info("You must input a number between 1 and 127"); } if (reg.getState() == RegistrationState.ALLOW_BANS) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); ResultSet rs = ps.executeQuery(); if (rs.next()) { _log.info("A game server is already registered on ID " + reg.getId()); reg.setState(RegistrationState.INITIAL_CHOICE); } else _log.info("Allow account bans from this game server? [y/n]:"); ps.close(); } catch (SQLException e) { _log.error("Could not remove a game server!", e); } finally { L2Database.close(con); } } else if (reg.getState() == RegistrationState.REMOVE) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); int cnt = ps.executeUpdate(); if (cnt == 0) _log.info("No game server registered on ID " + reg.getId()); else _log.info("Game server removed."); ps.close(); } catch (SQLException e) { _log.error("Could not remove a game server!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } else if (reg.getState() == RegistrationState.GENERATE) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT authData FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); ResultSet rs = ps.executeQuery(); if (rs.next()) { reg.setAuth(rs.getString("authData")); byte[] b = HexUtil.hexStringToBytes(reg.getAuth()); Properties pro = new Properties(); pro.setProperty("ServerID", String.valueOf(reg.getId())); pro.setProperty("HexID", HexUtil.hexToString(b)); BufferedOutputStream os = new BufferedOutputStream( new FileOutputStream("hexid.txt")); pro.store(os, "the hexID to auth into login"); IOUtils.closeQuietly(os); _log.info("hexid.txt has been generated."); } else _log.info("No game server registered on ID " + reg.getId()); rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not generate hexid.txt!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } break; case ALLOW_BANS: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') reg.setTrusted(true); else if (line.charAt(0) == 'n') reg.setTrusted(false); else throw new IllegalArgumentException("Invalid choice."); byte[] auth = Rnd.nextBytes(new byte[BYTES]); reg.setAuth(HexUtil.bytesToHexString(auth)); Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)"); ps.setInt(1, reg.getId()); ps.setString(2, reg.getAuth()); ps.setBoolean(3, reg.isTrusted()); ps.executeUpdate(); ps.close(); _log.info("Registered game server on ID " + reg.getId()); _log.info("The authorization string is:"); _log.info(reg.getAuth()); _log.info("Use it when registering this login server."); _log.info("If you need a legacy hexid file, use the 'hexid' command."); } catch (SQLException e) { _log.error("Could not register gameserver!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; default: if (line.equals("list")) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver"); ResultSet rs = ps.executeQuery(); while (rs.next()) _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans")); rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not register gameserver!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } else if (line.equals("reg")) { _log.info("Enter the desired ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.ALLOW_BANS; } else if (line.equals("rem")) { _log.info("Enter game server ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.REMOVE; } else if (line.equals("hexid")) { _log.info("Enter game server ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.GENERATE; } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:SelectRecordsUsingPreparedStatement.java
public static void main(String[] args) { ResultSet rs = null; Connection conn = null;/* w ww .java 2 s . co m*/ PreparedStatement pstmt = null; try { conn = getConnection(); String query = "select deptno, deptname, deptloc from dept where deptno > ?"; pstmt = conn.prepareStatement(query); // create a statement pstmt.setInt(1, 1001); // set input parameter rs = pstmt.executeQuery(); // extract data from the ResultSet while (rs.next()) { int dbDeptNumber = rs.getInt(1); String dbDeptName = rs.getString(2); String dbDeptLocation = rs.getString(3); System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:PrintResultSet.java
public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc: Contacts"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT Name,Description,Qty,Cost FROM Stock"); ResultSetMetaData md = rs.getMetaData(); if (rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE) System.out.println("UPDATABLE"); else// ww w . jav a 2 s . com System.out.println("READ_ONLY"); int nColumns = md.getColumnCount(); for (int i = 1; i <= nColumns; i++) { System.out.print(md.getColumnLabel(i) + ((i == nColumns) ? "\n" : "\t")); } while (rs.next()) { rs.updateString("Street", "123 Main"); rs.updateRow(); for (int i = 1; i <= nColumns; i++) { System.out.print(rs.getString(i) + ((i == nColumns) ? "\n" : "\t")); } } }
From source file:DemoResultSetOracle.java
public static void main(String[] args) { Connection conn = null;//w ww. j av a 2s. c o m Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); System.out.println("conn=" + conn); // prepare query String query = "select id, name, age from employees"; // create a statement stmt = conn.createStatement(); // execute query and return result as a ResultSet rs = stmt.executeQuery(query); // extract data from the ResultSet while (rs.next()) { String id = rs.getString(1); String name = rs.getString(2); int age = rs.getInt(3); System.out.println("id=" + id); System.out.println("name=" + name); System.out.println("age=" + age); System.out.println("---------------"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { // release database resources try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getHSQLConnection(); System.out.println("Got Connection."); Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int,name varchar);"); st.executeUpdate("create view surveyView as (select * from survey);"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')"); ResultSet rs = null; PreparedStatement ps = null;/*from w ww.j a v a 2 s.c om*/ String query = "select id, name from survey where id = ?"; ps = conn.prepareStatement(query); // specify values for all input parameters ps.setInt(1, 001); // set the first parameter: id // now, PreparedStatement object is ready to be executed. rs = ps.executeQuery(); // iterate the result set object while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); System.out.println("[id=" + id + "][name=" + name + "]"); } // NOTE: you may use PreparedStatement as many times as you want // here we use it for another set of parameters: ps.setInt(1, 002); // set the first parameter: id // now, PreparedStatement object is ready to be executed. rs = ps.executeQuery(); // iterate the result set object while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); System.out.println("[id=" + id + "][name=" + name + "]"); } rs.close(); ps.close(); conn.close(); }
From source file:driver.ieSystem2.java
public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); boolean login = false; int check = 0; int id = 0;//w w w . j ava 2 s. c o m String user = ""; String pass = ""; Person person = null; Date day = null; JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project", JOptionPane.INFORMATION_MESSAGE); do { System.out.println("What do you want?"); System.out.println("press 1 : Login"); System.out.println("press 2 : Create New User"); System.out.println("Press 3 : Exit "); System.out.println(""); do { try { System.out.print("Enter: "); check = sc.nextInt(); } catch (InputMismatchException e) { JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE); sc.next(); } } while (check <= 1 && check >= 3); // EXIT if (check == 3) { System.out.println("Close Application"); System.exit(0); } // CREATE USER if (check == 2) { System.out.println("-----------------------------------------"); System.out.println("Create New User"); System.out.println("-----------------------------------------"); System.out.print("Account ID: "); id = sc.nextInt(); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); try { Person.createUser(id, user, pass, 0, 0, 0, 0, 0); System.out.println("-----------------------------------------"); System.out.println("Create Complete"); System.out.println("-----------------------------------------"); } catch (Exception e) { System.out.println("-----------------------------------------"); System.out.println("Error, Try again"); System.out.println("-----------------------------------------"); } } else if (check == 1) { // LOGIN do { System.out.println("-----------------------------------------"); System.out.println("LOGIN "); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); if (Person.checkUser(user, pass)) { System.out.println("-----------------------------------------"); System.out.println("Login Complete"); } else { System.out.println("-----------------------------------------"); System.out.println("Invalid Username / Password"); } } while (!Person.checkUser(user, pass)); } } while (check != 1); login = true; person = new Person(user); do { System.out.println("-----------------------------------------"); System.out.println("Hi " + person.getPerName()); System.out.println("Press 1 : Add Income"); System.out.println("Press 2 : Add Expense"); System.out.println("Press 3 : Add Save"); System.out.println("Press 4 : History"); System.out.println("Press 5 : Search"); System.out.println("Press 6 : Analytics"); System.out.println("Press 7 : Total"); System.out.println("Press 8 : All Summary"); System.out.println("Press 9 : Sign Out"); do { try { System.out.print("Enter : "); check = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid Input"); sc.next(); } } while (check <= 1 && check >= 5); // Add Income if (check == 1) { double Income; String catalog = ""; double IncomeTotal = 0; catalog = JOptionPane.showInputDialog("What is your income : "); Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addIncome(person.getPerId(), day, catalog, Income); person.update(); } //Add Expense else if (check == 2) { double Expense; String catalog = ""; catalog = JOptionPane.showInputDialog("What is your expense :"); Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addExpense(person.getPerId(), day, catalog, Expense); person.update(); } //Add Save else if (check == 3) { double Saving; double SavingTotal = 0; String catalog = ""; Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); SavingTotal += Saving; person.addSave(person.getPerId(), day, catalog, Saving); person.update(); } //History else if (check == 4) { String x; do { System.out.println("-----------------------------------------"); System.out.println("YOUR HISTORY"); System.out.println("Date Type Amount"); System.out.println("-----------------------------------------"); List<History> history = person.getHistory(); if (history != null) { int count = 1; for (History h : history) { if (count++ <= 1) { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } else { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } } } System.out.println("-----------------------------------------"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //Searh else if (check == 5) { try { Connection conn = ConnectionDB.getConnection(); long a = person.getPerId(); String NAME = "Salary"; PreparedStatement ps = conn.prepareStatement( "SELECT * FROM INCOME WHERE PERID = " + a + " and CATALOG LIKE '%" + NAME + "%' "); ResultSet rec = ps.executeQuery(); while ((rec != null) && (rec.next())) { System.out.print(rec.getDate("Days")); System.out.print(" - "); System.out.print(rec.getString("CATALOG")); System.out.print(" - "); System.out.print(rec.getDouble("AMOUNT")); System.out.print(" - "); } ps.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Analy else if (check == 6) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); System.out.println("-----------------------------------------"); System.out.println("Income : " + df.format((in / sum) * 100) + "%"); System.out.println("Expense : " + df.format((ex / sum) * 100) + "%"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //TOTAL else if (check == 7) { String x; do { System.out.println("-----------------------------------------"); System.out.println("TOTALSAVE TOTAL"); System.out.println( person.getTotalSave() + " Baht" + " " + person.getTotal() + " Baht"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //ALL Summy else if (check == 8) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); double a = ((in / sum) * 100); double b = ((ex / sum) * 100); System.out.println("-----------------------------------------"); System.out.println("ALL SUMMARY"); System.out.println("Account: " + person.getPerName()); System.out.println(""); System.out.println("Total Save ------------- Total"); System.out .println(person.getTotalSave() + " Baht " + person.getTotal() + " Baht"); System.out.println(""); System.out.println("INCOME --------------- EXPENSE"); System.out.println(df.format(a) + "%" + " " + df.format(b) + "%"); System.out.println("-----------------------------------------"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //LOG OUT else { System.out.println("See ya.\n"); login = false; break; } } while (true); }
From source file:Main.java
public static void main(String[] args) throws Exception { String deptName = "oldName"; String newDeptName = "newName"; ResultSet rs = null; Connection conn = null;//ww w . j a v a 2s.c o m PreparedStatement pstmt = null; PreparedStatement pstmt2 = null; try { conn = getConnection(); // prepare query for getting a REF object and PrepareStatement object String refQuery = "select manager from dept_table where dept_name=?"; pstmt = conn.prepareStatement(refQuery); pstmt.setString(1, deptName); rs = pstmt.executeQuery(); java.sql.Ref ref = null; if (rs.next()) { ref = rs.getRef(1); } if (ref == null) { System.out.println("error: could not get a reference for manager."); System.exit(1); } String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)"; pstmt2 = conn.prepareStatement(query); pstmt2.setString(1, newDeptName); pstmt2.setRef(2, ref); // execute query, and return number of rows created int rowCount = pstmt2.executeUpdate(); System.out.println("rowCount=" + rowCount); } finally { pstmt.close(); pstmt2.close(); conn.close(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String deptName = "oldName"; String newDeptName = "newName"; ResultSet rs = null; Connection conn = null;/*from ww w . j a va 2 s .c o m*/ PreparedStatement pstmt = null; PreparedStatement pstmt2 = null; try { conn = getConnection(); // prepare query for getting a REF object and PrepareStatement object String refQuery = "select manager from dept_table where dept_name=?"; pstmt = conn.prepareStatement(refQuery); pstmt.setString(1, deptName); rs = pstmt.executeQuery(); java.sql.Ref ref = null; if (rs.next()) { ref = rs.getRef("manager"); } if (ref == null) { System.out.println("error: could not get a reference for manager."); System.exit(1); } String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)"; pstmt2 = conn.prepareStatement(query); pstmt2.setString(1, newDeptName); pstmt2.setRef(2, ref); // execute query, and return number of rows created int rowCount = pstmt2.executeUpdate(); System.out.println("rowCount=" + rowCount); } finally { pstmt.close(); pstmt2.close(); conn.close(); } }
From source file:InsertRow.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/* www . ja va 2 s. c om*/ Statement stmt; String query = "select COF_NAME, PRICE from COFFEES"; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); uprs.moveToInsertRow(); uprs.updateString("COF_NAME", "Kona"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 10.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.beforeFirst(); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String s = uprs.getString("COF_NAME"); int sup = uprs.getInt("SUP_ID"); float f = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int t = uprs.getInt("TOTAL"); System.out.print(s + " " + sup + " " + f + " "); System.out.println(sales + " " + t); } uprs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }