List of usage examples for java.sql ResultSet getString
String getString(String columnLabel) throws SQLException;
ResultSet
object as a String
in the Java programming language. From source file:ResultSetMetaDataExample.java
public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:Inventory", "", ""); Statement stmt = con.createStatement(); boolean notDone = true; String sqlStr = null;//from ww w .jav a2s. c om BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (notDone) { sqlStr = br.readLine(); if (sqlStr.startsWith("SELECT") || sqlStr.startsWith("select")) { ResultSet rs = stmt.executeQuery(sqlStr); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int x = 1; x <= columnCount; x++) { String columnName = rsmd.getColumnName(x); System.out.print(columnName); } while (rs.next()) { for (int x = 1; x <= columnCount; x++) { if (rsmd.getColumnTypeName(x).compareTo("CURRENCY") == 0) System.out.print("$"); String resultStr = rs.getString(x); System.out.print(resultStr + "\t"); } } } else if (sqlStr.startsWith("exit")) notDone = false; } stmt.close(); con.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { try {//w w w . j a v a 2 s.c o m String url = "jdbc:odbc:yourdatabasename"; String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String user = "guest"; String password = "guest"; Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String sqlQuery = "SELECT EMPNO, EName, Job, MGR, HIREDATE FROM EMP"; ResultSet rs = stmt.executeQuery(sqlQuery); int rowSize = 0; while (rs.next()) { rowSize++; } System.out.println("Number of Rows in ResultSet is: " + rowSize); if (rowSize == 0) { System.out.println("Since there are no rows, exiting..."); System.exit(0); } int cursorPosition = Math.round(rowSize / 2); System.out.println("Moving to position: " + cursorPosition); rs.absolute(cursorPosition); System.out.println("Name: " + rs.getString(2)); rs.relative(-1); cursorPosition = rs.getRow(); System.out.println("Moving to position: " + cursorPosition); System.out.println("Name: " + rs.getString(2)); System.out.println("Moving to the first row"); while (!rs.isFirst()) { rs.previous(); } System.out.println("Name: " + rs.getString(2)); connection.close(); } catch (Exception e) { System.err.println(e); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String url = "jdbc:mysql://192.168.100.100:3306/"; String dbName = "databaseName"; Statement stmt = null;//from w w w.ja v a2s . c om ResultSet result = null; String driver = "com.mysql.jdbc.Driver"; String databaseUserName = "admin"; String databasePassword = "root"; Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword); stmt = conn.createStatement(); result = null; String password, username; result = stmt.executeQuery("select * from userTable where username ='user1' "); if (!result.isBeforeFirst()) { System.out.println("resultset contin no rows"); } while (result.next()) { username = result.getString("username"); password = result.getString("password"); System.out.println(username + " " + password); } conn.close(); }
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//from w ww .j av 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:JOCLPoolingDriverExample.java
public static void main(String[] args) { //// w ww.jav a 2s . c o m // Just plain-old JDBC. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = DriverManager.getConnection(args[0]); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:BasicDataSourceExample.java
public static void main(String[] args) { // First we set up the BasicDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. ///* ww w.j ava 2s.c o m*/ System.out.println("Setting up data source."); DataSource dataSource = setupDataSource(args[0]); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:ReverseSelect.java
public static void main(String argv[]) { Connection con = null;//from w w w .j a v a 2s .com try { String url = "jdbc:msql://carthage.imaginary.com/ora"; String driver = "com.imaginary.sql.msql.MsqlDriver"; Properties p = new Properties(); Statement stmt; ResultSet rs; p.put("user", "borg"); Class.forName(driver).newInstance(); con = DriverManager.getConnection(url, "borg", ""); stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery("SELECT * from test ORDER BY test_id"); // as a new ResultSet, rs is currently positioned // before the first row System.out.println("Got results:"); // position rs after the last row rs.afterLast(); while (rs.previous()) { int a = rs.getInt("test_id"); String str = rs.getString("test_val"); System.out.print("\ttest_id= " + a); System.out.println("/str= '" + str + "'"); } System.out.println("Done."); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
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. ja va 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:TestBatchUpdate.java
public static void main(String args[]) { Connection conn = null;// w w w . ja v a 2 s . c o m Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); conn.setAutoCommit(false); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('11', 'A')"); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('22', 'B')"); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('33', 'C')"); int[] updateCounts = stmt.executeBatch(); conn.commit(); rs = stmt.executeQuery("SELECT * FROM batch_table"); while (rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); System.out.println("id=" + id + " name=" + name); } } catch (BatchUpdateException b) { System.err.println("SQLException: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor error code: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor error code: " + ex.getErrorCode()); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (Exception ignore) { } } }
From source file:javax.arang.DB.dbcp.BasicDataSourceExample.java
public static void main(String[] args) { // First we set up the BasicDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. ///*from w ww . ja va 2s .co m*/ System.out.println("Setting up data source."); DataSource dataSource = setupDataSource("jdbc:mysql://localhost:3306/FX"); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery("select * from users"); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }