List of usage examples for java.sql Connection close
void close() throws SQLException;
Connection
object's database and JDBC resources immediately instead of waiting for them to be automatically released. 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')"); PreparedStatement pstmt = null; ParameterMetaData paramMetaData = null; String query = "select * from survey where id > ? and name = ?"; pstmt = conn.prepareStatement(query); paramMetaData = pstmt.getParameterMetaData(); if (paramMetaData == null) { System.out.println("db vendor does NOT support ParameterMetaData"); } else {/*from w ww. j a v a2s . co m*/ System.out.println("db vendor supports ParameterMetaData"); // find out the number of dynamic parameters int paramCount = paramMetaData.getParameterCount(); System.out.println("paramCount=" + paramCount); } pstmt.close(); conn.close(); }
From source file:MainClass.java
public static void main(String[] args) { Connection connection = null; Statement statement = null;/* w w w . j a va2 s . co m*/ ResultSet resultSet = null; try { connection = getConnection(); // Do work with connection statement = connection.createStatement(); String selectEmployeesSQL = "SELECT * FROM employees"; resultSet = statement.executeQuery(selectEmployeesSQL); while (resultSet.next()) { printEmployee(resultSet); } } catch (Exception e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } // nothing we can do } if (statement != null) { try { statement.close(); } catch (SQLException e) { } // nothing we can do } if (connection != null) { try { connection.close(); } catch (SQLException e) { } // nothing we can do } } }
From source file:JDBCQuery.java
public static void main(String[] av) { try {//from w w w. j a va 2s . com System.out.println("Loading Driver (with Class.forName)"); // Load the jdbc-odbc bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Enable logging // DriverManager.setLogStream(System.err); System.out.println("Getting Connection"); Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd // Any warnings generated by the connect? checkForWarning(conn.getWarnings()); System.out.println("Creating Statement"); Statement stmt = conn.createStatement(); System.out.println("Executing Query"); ResultSet rs = stmt.executeQuery("SELECT * FROM Companies"); System.out.println("Retrieving Results"); int i = 0; while (rs.next()) { System.out.println("Retrieving Company ID"); int x = rs.getInt("CustNO"); System.out.println("Retrieving Name"); String s = rs.getString("Company"); System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + "."); } rs.close(); // All done with that resultset stmt.close(); // All done with that statement conn.close(); // All done with that DB connection } catch (ClassNotFoundException e) { System.out.println("Can't load driver " + e); } catch (SQLException e) { System.out.println("Database access failed " + e); } }
From source file:Main.java
public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String URL = "jdbc:odbc:dbname"; Connection dbConn = DriverManager.getConnection(URL, "user", "passw"); Employee employee = new Employee(42, "AA", 9); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(employee);// www. ja v a 2s .c om byte[] employeeAsBytes = baos.toByteArray(); PreparedStatement pstmt = dbConn.prepareStatement("INSERT INTO EMPLOYEE (emp) VALUES(?)"); ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes); pstmt.setBinaryStream(1, bais, employeeAsBytes.length); pstmt.executeUpdate(); pstmt.close(); Statement stmt = dbConn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT emp FROM Employee"); while (rs.next()) { byte[] st = (byte[]) rs.getObject(1); ByteArrayInputStream baip = new ByteArrayInputStream(st); ObjectInputStream ois = new ObjectInputStream(baip); Employee emp = (Employee) ois.readObject(); } stmt.close(); rs.close(); dbConn.close(); }
From source file:DemoPreparedStatementSetBlob.java
public static void main(String[] args) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null;/*from www. j av a 2s . c o m*/ java.sql.Blob blob = null; try { conn = getConnection(); // prepare blob object from an existing binary column pstmt = conn.prepareStatement("select photo from my_pictures where id = ?"); pstmt.setString(1, "0001"); rs = pstmt.executeQuery(); rs.next(); blob = rs.getBlob(1); // prepare SQL query for inserting a new row using setBlob() String query = "insert into blob_table(id, blob_column) values(?, ?)"; // begin transaction conn.setAutoCommit(false); pstmt = conn.prepareStatement(query); pstmt.setString(1, "0002"); pstmt.setBlob(2, blob); int rowCount = pstmt.executeUpdate(); System.out.println("rowCount=" + rowCount); // end transaction conn.commit(); } finally { rs.close(); pstmt.close(); conn.close(); } }
From source file:ex4.java
public static void main(String[] params) { CommandLine commandLine = null;/* w ww . ja va 2s . c om*/ String sqlpath = "", host = "", port = "3306", username = "", password = "", database = ""; Boolean query = false; Option option_sql = Option.builder("s").argName("sql").hasArg() .desc("Path to a file containing a valid MySQL sql statement").build(); Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname") .build(); Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build(); Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username") .build(); Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password") .build(); Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name") .build(); Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build(); Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build(); Options options = new Options(); CommandLineParser parser = new DefaultParser(); options.addOption(option_sql); options.addOption(option_hostname); options.addOption(option_port); options.addOption(option_username); options.addOption(option_password); options.addOption(option_dbname); options.addOption(option_query); options.addOption(option_help); try { commandLine = parser.parse(options, params); } catch (MissingOptionException e) { help(options); } catch (MissingArgumentException e) { help(options); } catch (ParseException e) { System.out.println(e); } if (commandLine.hasOption("w") || params.length == 0) { help(options); } if (commandLine.hasOption("s")) { sqlpath = commandLine.getOptionValue("s"); } else { System.out.println("Missing path to a SQL statement file"); help(options); } if (commandLine.hasOption("h")) { host = commandLine.getOptionValue("h"); } else { System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)"); help(options); } if (commandLine.hasOption("n")) { port = commandLine.getOptionValue("n"); } else { System.out.println("Missing ClearDB Port Value. Defaulting to 3306"); } if (commandLine.hasOption("u")) { username = commandLine.getOptionValue("u"); } else { System.out.println("Missing ClearDB Username"); help(options); } if (commandLine.hasOption("p")) { password = commandLine.getOptionValue("p"); } else { System.out.println("Missing ClearDB Password"); help(options); } if (commandLine.hasOption("d")) { database = commandLine.getOptionValue("d"); } else { System.out.println("Missing ClearDB Database Name"); help(options); } if (commandLine.hasOption("query")) { query = true; } String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port) .append("/").append(database).append("?reconnect=true").toString(); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println(e); } try { Connection con = DriverManager.getConnection(connectionURL, username, password); Statement stmt = con.createStatement(); if (query) { System.out.println("Querying target MySQL DB ..."); ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset())); while (rs.next()) System.out.println(rs.getInt("emp_no") + " " + rs.getDate("birth_date") + " " + rs.getString("first_name") + " " + rs.getString("last_name") + " " + rs.getString("gender") + " " + rs.getDate("hire_date")); } else { System.out.println("Updating target MySQL DB ..."); int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset())); System.out.println(result); } con.close(); } catch (Exception e) { System.out.println(e); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,null)"); st.executeUpdate("insert into survey (id,name ) values (3,'Tom')"); ResultSet rs = st.executeQuery("SELECT * FROM survey"); // extract data from the ResultSet scroll from top while (rs.next()) { String id = rs.getString(1); String name = rs.getString(2); System.out.println("id=" + id + " name=" + name); }//from w ww . ja va 2 s .com System.out.println("---------"); // scroll from the bottom rs.afterLast(); while (rs.previous()) { String id = rs.getString(1); String name = rs.getString(2); System.out.println("id=" + id + " name=" + name); } rs.close(); st.close(); conn.close(); }
From source file:AutoGenKeys.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null; PreparedStatement pstmt;/*from w w w .j a v a 2 s .c om*/ String insert = "INSERT INTO COFFEES VALUES ('HYPER_BLEND', " + "101, 10.99, 0, 0)"; String update = "UPDATE COFFEES SET PRICE = ? WHERE KEY = ?"; 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"); pstmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS); pstmt.executeUpdate(); ResultSet keys = pstmt.getGeneratedKeys(); int count = 0; keys.next(); int key = keys.getInt(1); pstmt = con.prepareStatement(update); pstmt.setFloat(1, 11.99f); pstmt.setInt(2, key); pstmt.executeUpdate(); keys.close(); pstmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null;/*w w w.j a v a 2 s. com*/ Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "UPDATE Registration SET age = 30 WHERE id in (1, 2)"; stmt.executeUpdate(sql); sql = "SELECT id, first, last, age FROM Person"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("firstName"); String last = rs.getString("lastName"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); stmt.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", ""); Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = statement.executeQuery("SELECT * FROM products"); while (resultSet.next()) { String productCode = resultSet.getString("product_code"); String productName = resultSet.getString("product_name"); int quantity = resultSet.getInt("quantity"); double price = resultSet.getDouble("price"); System.out.println(productCode + "\t" + productName + "\t" + quantity + "\t" + price); }/* w ww.ja v a 2 s . c o m*/ while (resultSet.previous()) { String productCode = resultSet.getString("product_code"); String productName = resultSet.getString("product_name"); int quantity = resultSet.getInt("quantity"); double price = resultSet.getDouble("price"); System.out.println(productCode + "\t" + productName + "\t" + quantity + "\t" + price); } connection.close(); }