List of usage examples for java.sql Statement execute
boolean execute(String sql) throws SQLException;
From source file:com.bloidonia.vertx.mods.JdbcProcessor.java
private void doExecute(Message<JsonObject> message, Connection connection, TransactionalHandler transaction) throws SQLException { Statement statement = null; try {/* w w w . ja v a2 s . co m*/ statement = connection.createStatement(); statement.execute(message.body().getString("stmt")); if (transaction == null) { sendOK(message); } else { JsonObject reply = new JsonObject(); reply.putString("status", "ok"); message.reply(reply, transaction); } } finally { SilentCloser.close(statement); } }
From source file:edu.ku.brc.specify.toycode.mexconabio.FileMakerToMySQL.java
/** * // w w w.j a va 2 s .c o m */ public FileMakerToMySQL(final String tableName, final String keyField, final boolean doAddKey) { super(); this.tableName = tableName; this.keyField = keyField; this.doAddKey = doAddKey; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/" + dbName + "?characterEncoding=UTF-8&autoReconnect=true", userName, password); Statement stmt = conn.createStatement(); stmt.execute("DROP TABLE " + tableName); stmt.close(); } catch (SQLException ex) { ex.printStackTrace(); } }
From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java
private void dropObject(Connection conn, String objectType, String objectName) throws SQLException { Statement stmt = null; try {/*from w w w.j a va2s . c o m*/ stmt = conn.createStatement(); String cascade = (StringUtils.equalsIgnoreCase(objectType, "TABLE")) ? " CASCADE CONSTRAINTS" : ""; String sql = "DROP " + objectType + " " + objectName + cascade; System.err.println(sql); stmt.execute(sql); } catch (SQLException e) { throw e; } finally { StatementUtil.close(stmt); } }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testUUIDGeneratedKeys() throws SQLException { Statement stat = conn.createStatement(); stat.execute("CREATE TABLE TEST_UUID(id UUID DEFAULT random_UUID() PRIMARY KEY)"); stat.execute("INSERT INTO TEST_UUID() VALUES()"); ResultSet rs = stat.getGeneratedKeys(); rs.next();//from w ww . j a v a2s .com byte[] data = rs.getBytes(1); assertEquals(16, data.length); stat.execute("INSERT INTO TEST_UUID VALUES(random_UUID())"); rs = stat.getGeneratedKeys(); assertFalse(rs.next()); stat.execute("DROP TABLE TEST_UUID"); }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testUUID() throws SQLException { Statement stat = conn.createStatement(); stat.execute("create table test_uuid(id uuid primary key)"); UUID uuid = new UUID(-2, -1); PreparedStatement prep = conn.prepareStatement("insert into test_uuid values(?)"); prep.setObject(1, uuid);//from w ww . j av a 2s.co m prep.execute(); ResultSet rs = stat.executeQuery("select * from test_uuid"); rs.next(); assertEquals("ffffffff-ffff-fffe-ffff-ffffffffffff", rs.getString(1)); Object o = rs.getObject(1); assertEquals("java.util.UUID", o.getClass().getName()); stat.execute("drop table test_uuid"); }
From source file:coral.data.DataServiceJbdcImpl.java
public DataServiceJbdcImpl(String dbname, boolean setup, String dbmode) { // Load the HSQL Database Engine JDBC driver // hsqldb.jar should be in the class path or made part of the current // jar/* ww w.j a va 2s . com*/ try { Class.forName("org.hsqldb.jdbcDriver"); // connect to the database. This will load the db files and start // the // database if it is not already running. // db_file_name_prefix is used to open or create files that hold the // state // of the db. // It can contain directory names relative to the // current working directory conn = DriverManager.getConnection("jdbc:hsqldb:" + dbmode + ":" + dbname + "/exp.db", // filenames "sa", // username ""); if (dbmode.equals("mem") || setup) { logger.info("SETUP DATABASE"); Statement stat = conn.createStatement(); // stat.execute("delete from datas;"); // stat.execute("delete from states;"); stat.execute("drop table if exists datas;"); stat.execute( "CREATE TABLE datas ( id BIGINT, collection VARCHAR(10), name VARCHAR(80), value VARCHAR(1024));"); stat.execute("CREATE INDEX idatas ON datas ( id, name );"); stat.execute("drop table if exists states;"); stat.execute( "CREATE TABLE states ( id BIGINT, collection VARCHAR(10), template VARCHAR(80), block INTEGER, round INTEGER, stage INTEGER, msg VARCHAR(255));"); stat.execute("COMMIT"); conn.commit(); stat.close(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
From source file:amp.lib.io.db.Database.java
/** * Execute an SQL statement and report its execution to any listeners. Terminal semicolon added * if needed.//from w w w .j a v a 2s .c o m * @param statement the statement to execute */ public void execute(String statement) { statement = statement.trim(); if (statement.length() == 0) { return; } if (!statement.endsWith(";")) { statement = statement + ";"; } try { Statement stmt = getConnection().createStatement(); stmt.execute(statement); Report.okay("\n" + statement); } catch (Exception e) { throw new RuntimeException("\n" + statement + "\n" + e.getMessage()); } }
From source file:com.diversityarrays.dal.server.SqlWorker.java
public Response createResponse(SqlResponseType rtype, String sql, String metaTagName, Transformer<Boolean, DalResponseBuilder> builderFactory) { if (metaTagName == null && !rtype.isText()) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new IllegalArgumentException("No metaTagName supplied for rtype=" + rtype).printStackTrace(pw); pw.close();/*from w ww. j av a 2 s .com*/ return new Response(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, sw.toString()); } Response result; Statement stmt = null; ResultSet rs = null; try { Connection conn = getConnection(); stmt = conn.createStatement(); if (rtype.isText()) { StringBuilder sb = new StringBuilder("<html><body>"); sb.append("<code>").append(DbUtil.htmlEscape(sql)).append("</code><hr/>"); boolean hasResultSet = stmt.execute(sql); if (hasResultSet) { rs = stmt.getResultSet(); DalServerUtil.appendResultSetRowsAsTable("No data rows returned", rs, sb); sb.append("</body></html>"); } else { int n = stmt.getUpdateCount(); sb.append("Update count=").append(n); } result = new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, sb.toString()); } else { if (verbose) { System.err.println("sql: " + sql); } DalResponseBuilder builder = builderFactory == null ? DalServerUtil.createBuilder(rtype.isJson()) : builderFactory.transform(rtype.isJson()); boolean hasResultSet = stmt.execute(sql); if (hasResultSet) { rs = stmt.getResultSet(); DalServerUtil.appendResultSetRows(rs, builder, metaTagName); result = builder.build(Response.Status.OK); } else { int n = stmt.getUpdateCount(); builder.startTag(DALClient.TAG_INFO).attribute(DALClient.ATTR_MESSAGE, "Update Count=" + n) .endTag(); result = builder.build(Response.Status.OK); } } } catch (SQLException e) { // Once for the log e.printStackTrace(); if (SqlResponseType.TEXT == rtype) { // Browser request gets it all as text StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.close(); result = new Response(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, sw.toString()); } else { // DAL client gets just the message part result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage()); } } catch (DalDbException e) { result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage()); } finally { SqlUtil.closeSandRS(stmt, rs); } return result; }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testSetObject() throws SQLException { Statement stat = conn.createStatement(); stat.execute("CREATE TABLE TEST(C CHAR(1))"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?)"); prep.setObject(1, 'x'); prep.execute();// ww w .jav a 2 s . c o m stat.execute("DROP TABLE TEST"); stat.execute("CREATE TABLE TEST(ID INT, DATA BINARY, JAVA OTHER)"); prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?)"); prep.setInt(1, 1); prep.setObject(2, 11); prep.setObject(3, null); prep.execute(); prep.setInt(1, 2); prep.setObject(2, 101, Types.OTHER); prep.setObject(3, 103, Types.OTHER); prep.execute(); PreparedStatement p2 = conn.prepareStatement("SELECT * FROM TEST ORDER BY ID"); ResultSet rs = p2.executeQuery(); rs.next(); Object o = rs.getObject(2); assertTrue(o instanceof byte[]); assertTrue(rs.getObject(3) == null); rs.next(); o = rs.getObject(2); assertTrue(o instanceof byte[]); o = rs.getObject(3); assertTrue(o instanceof Integer); assertEquals(103, ((Integer) o).intValue()); assertFalse(rs.next()); stat.execute("DROP TABLE TEST"); }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testParameterMetaData() throws SQLException { PreparedStatement prep = conn.prepareStatement("SELECT ?, ?, ? FROM DUAL"); ParameterMetaData pm = prep.getParameterMetaData(); assertEquals("java.lang.String", pm.getParameterClassName(1)); assertEquals("VARCHAR", pm.getParameterTypeName(1)); assertEquals(3, pm.getParameterCount()); assertEquals(ParameterMetaData.parameterModeIn, pm.getParameterMode(1)); assertEquals(Types.VARCHAR, pm.getParameterType(1)); assertEquals(0, pm.getPrecision(1)); assertEquals(0, pm.getScale(1));// w ww.j a va2s.c o m assertEquals(ResultSetMetaData.columnNullableUnknown, pm.isNullable(1)); assertEquals(pm.isSigned(1), true); assertThrows(SQLErrorCode.INVALID_VALUE_2, pm).getPrecision(0); assertThrows(SQLErrorCode.INVALID_VALUE_2, pm).getPrecision(4); prep.close(); assertThrows(SQLErrorCode.OBJECT_CLOSED, pm).getPrecision(1); Statement stat = conn.createStatement(); stat.execute("CREATE TABLE TEST3(ID INT, NAME VARCHAR(255), DATA DECIMAL(10,2))"); PreparedStatement prep1 = conn.prepareStatement("UPDATE TEST3 SET ID=?, NAME=?, DATA=?"); PreparedStatement prep2 = conn.prepareStatement("INSERT INTO TEST3 VALUES(?, ?, ?)"); checkParameter(prep1, 1, "java.lang.Integer", 4, "INTEGER", 10, 0); checkParameter(prep1, 2, "java.lang.String", 12, "VARCHAR", 255, 0); checkParameter(prep1, 3, "java.math.BigDecimal", 3, "DECIMAL", 10, 2); checkParameter(prep2, 1, "java.lang.Integer", 4, "INTEGER", 10, 0); checkParameter(prep2, 2, "java.lang.String", 12, "VARCHAR", 255, 0); checkParameter(prep2, 3, "java.math.BigDecimal", 3, "DECIMAL", 10, 2); PreparedStatement prep3 = conn .prepareStatement("SELECT * FROM TEST3 WHERE ID=? AND NAME LIKE ? AND ?>DATA"); checkParameter(prep3, 1, "java.lang.Integer", 4, "INTEGER", 10, 0); checkParameter(prep3, 2, "java.lang.String", 12, "VARCHAR", 0, 0); checkParameter(prep3, 3, "java.math.BigDecimal", 3, "DECIMAL", 10, 2); stat.execute("DROP TABLE TEST3"); }