Java Code Examples for java.sql.Connection.createStatement()

The following are Jave code examples for showing how to use createStatement() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Automekanik   File: ShikoKonsumatoret.java   View Source Code Vote up 9 votes
public void mbushTabelen(){
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select * from Konsumatori");
                ObservableList<TabelaKonsumatori> data = FXCollections.observableArrayList();
                while (rs.next()){
                    data.add(new TabelaKonsumatori(rs.getInt("id"), rs.getString("emri"), rs.getString("mbiemri"),
                            rs.getString("makina"), rs.getString("komuna"), rs.getString("pershkrimi")));
                }
                table.setItems(data);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    });
    t.start();
}
 
Example 2
Project: aliyun-maxcompute-data-collectors   File: OracleUtils.java   View Source Code Vote up 7 votes
/**
 * Drop a table if it exists.
 */
public static void dropTable(String tableName, ConnManager manager)
    throws SQLException {
  Connection connection = null;
  Statement st = null;

  try {
    connection = manager.getConnection();
    connection.setAutoCommit(false);
    st = connection.createStatement();

    // create the database table and populate it with data.
    st.executeUpdate(getDropTableStatement(tableName));

    connection.commit();
  } finally {
    try {
      if (null != st) {
        st.close();
      }
    } catch (SQLException sqlE) {
      LOG.warn("Got SQLException when closing connection: " + sqlE);
    }
  }
}
 
Example 3
Project: spr   File: SqlUpdates.java   View Source Code Vote up 7 votes
public static void updateUnidadMedida(String id, String nombre,
		String abrev, String simbolo, String descripcion) {
	Connection conect = ConnectionConfiguration.conectar();
	Statement statement = null;
	String query = "update unidad_medida set ";
	// if (id!="") query+= "id=\""+id+"\", ";
	if (nombre != "")
		query += "nombre=\"" + nombre + "\", ";
	if (abrev != "")
		query += "abrev=\"" + abrev + "\", ";
	if (simbolo != "")
		query += "simbolo=\"" + simbolo + "\", ";
	if (descripcion != "")
		query += "descripcion=\"" + descripcion + "\", ";
	query = query.substring(0, query.length() - 2);
	query += "where id=" + id;

	try {
		statement = conect.createStatement();
		statement.execute(query);
		conect.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 4
Project: alchem   File: ViewSaleController.java   View Source Code Vote up 6 votes
public ObservableList<Sale> getList(String sqlQuery, ObservableList<Sale> saleListDetails) {
    String date, patientName, doctorName, companyName, mode;
    Long billNumber;
    Float amount;
    try {
        Connection dbConnection = JDBC.databaseConnect();
        Statement sqlStatement = dbConnection.createStatement();
        ResultSet saleResultSet = sqlStatement.executeQuery(sqlQuery);
        while (saleResultSet.next()) {
            date = saleResultSet.getString("date");
            patientName = saleResultSet.getString("patient_name");
            companyName = saleResultSet.getString("company");
            doctorName = saleResultSet.getString("doctor_name");
            mode = saleResultSet.getString("mode");
            billNumber = saleResultSet.getLong("bill_no");
            amount = saleResultSet.getFloat("total_amount");
            saleListDetails.add(new Sale(date, billNumber, patientName, doctorName, companyName, mode, amount));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return saleListDetails;
}
 
Example 5
Project: avengers-db   File: TeamDAO.java   View Source Code Vote up 6 votes
public Team findTeamById(String term) throws SQLException {

		String query = "SELECT t.team_id, t.team_name, t.history, t.picture AS team_picture, h.name AS hero_name, h.picture AS hero_picture "
				+ "FROM team t LEFT JOIN team_hero th ON t.team_id = th.team_id "
				+ "LEFT JOIN heroes h ON th.hero_id = h.id " + "WHERE t.team_id='"+ term + "'";

		Connection connect = connectToMySQL();
		Statement statement = connect.createStatement();
		ResultSet resultSet = statement.executeQuery(query);
		if (resultSet.next()) {
			Team team = resultSetToTeam(resultSet);
			connect.close();
			return team;
		} else {
			connect.close();
			return null;
		}
	}
 
Example 6
Project: parabuild-ci   File: UpgraderToVersion65.java   View Source Code Vote up 6 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    LOG.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{
            " alter table TEST_CASE drop constraint TEST_CASE_UC2",
            " alter table TEST_CASE add constraint TEST_CASE_UC2 unique (TEST_PACKAGE_ID, NAME)",
    });

    LOG.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

  } finally {
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 7
Project: letv   File: Database.java   View Source Code Vote up 6 votes
public boolean query(String sql) {
    try {
        Statement stmt = getStatement();
        if (stmt != null) {
            stmt.close();
        }
        ResultSet rs = getResultSet();
        if (rs != null) {
            rs.close();
        }
        Connection con = getConnection();
        if (con == null) {
            return false;
        }
        stmt = con.createStatement();
        setStatement(stmt);
        setResultSet(stmt.executeQuery(sql));
        return true;
    } catch (Exception e) {
        Debug.warning(e);
        return false;
    }
}
 
Example 8
Project: oscm   File: PropertyImport.java   View Source Code Vote up 6 votes
private void initStartCount(Connection conn) {
    try {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt
                .executeQuery("SELECT MAX(TKEY) FROM " + TABLE_NAME);
        while (rs.next()) {
            count = rs.getInt(1);
        }
        rs.close();
        stmt.close();
    } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(
                "Could not determine max id value in use.");
    }

}
 
Example 9
Project: tcp   File: SqlUpdates.java   View Source Code Vote up 6 votes
public static boolean borradoSprProducto(SprProducto objeto, String usuarioResponsable){
  	 Connection conect=ConnectionConfiguration.conectar();
  	 Statement statement = null;
  	 objeto.changeBorrado();
  	 
	 String query = "update spr_producto set borrado='"+objeto.isBorrado()+"'";
	 		query += ", usuario_responsable='" + usuarioResponsable + "'";	
	 
	 query+=" where id ="+objeto.getId(); 	
	 try {
		statement=conect.createStatement();
		statement.execute(query);
	    conect.close();
	    return true;
	 }catch (SQLException e) {e.printStackTrace(); return false;}
}
 
Example 10
Project: spr   File: SqlUpdates.java   View Source Code Vote up 5 votes
public static void updateObjetoDeGasto(String id, String nombre,
		String descripcion, String abrev, String es_imputable,
		String numero_fila, String anho) {
	Connection conect = ConnectionConfiguration.conectar();
	Statement statement = null;
	String query = "update objeto_de_gasto set ";
	// if (id!="") query+= "id=\""+id+"\", ";
	if (nombre != "")
		query += "nombre=\"" + nombre + "\", ";
	if (descripcion != "")
		query += "descripcion=\"" + descripcion + "\", ";
	if (abrev != "")
		query += "abrev=\"" + abrev + "\", ";
	if (es_imputable != "")
		query += "es_imputable=\"" + es_imputable + "\", ";
	if (anho != "")
		query += "anho=\"" + anho + "\", ";
	query = query.substring(0, query.length() - 2);
	query += "where id=" + id;

	try {
		statement = conect.createStatement();
		statement.execute(query);
		conect.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 11
Project: tcp   File: SqlSelects.java   View Source Code Vote up 5 votes
public static List<LaHasAreasAga> selectLaHasAreasAga(String conditionLaHasAreasAga) throws SQLException{
	Connection conect=ConnectionConfiguration.conectar();
	String query = " select * from la_has_areas_aga "+conditionLaHasAreasAga;

	Statement statement = null;
	ResultSet rs=null;
	List<LaHasAreasAga> objetos = new ArrayList<LaHasAreasAga>();

	try {
		statement = conect.createStatement();
		rs=statement.executeQuery(query);
		while(rs.next()){
			LaHasAreasAga objeto = new LaHasAreasAga();
	
			objeto.setLineaAccionId(rs.getInt("linea_accion_id"));
			objeto.setAreasAgaId(rs.getInt("areas_aga_id"));
			
			objetos.add(objeto);
		}
	}
	catch (SQLException e) {e.printStackTrace();}
	finally{
		if (statement != null) {statement.close();}
		if (conect != null) {conect.close();}
	}
	return objetos; 
}
 
Example 12
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View Source Code Vote up 5 votes
/**
 * Tests fix for Bug#23212347, ALL API CALLS ON RESULTSET METADATA RESULTS IN NPE WHEN USESERVERPREPSTMTS=TRUE.
 */
public void testBug23212347() throws Exception {
    boolean useSPS = false;
    do {
        String testCase = String.format("Case [SPS: %s]", useSPS ? "Y" : "N");
        createTable("testBug23212347", "(id INT)");

        Properties props = new Properties();
        props.setProperty("useServerPrepStmts", Boolean.toString(useSPS));

        Connection testConn = getConnectionWithProps(props);
        Statement testStmt = testConn.createStatement();
        testStmt.execute("INSERT INTO testBug23212347 VALUES (1)");

        this.pstmt = testConn.prepareStatement("SELECT * FROM testBug23212347 WHERE id = 1");
        this.rs = this.pstmt.executeQuery();
        assertTrue(testCase, this.rs.next());
        assertEquals(testCase, 1, this.rs.getInt(1));
        assertFalse(testCase, this.rs.next());
        ResultSetMetaData rsmd = this.pstmt.getMetaData();
        assertEquals(testCase, "id", rsmd.getColumnName(1));

        this.pstmt = testConn.prepareStatement("SELECT * FROM testBug23212347 WHERE id = ?");
        this.pstmt.setInt(1, 1);
        this.rs = this.pstmt.executeQuery();
        assertTrue(testCase, this.rs.next());
        assertEquals(testCase, 1, this.rs.getInt(1));
        assertFalse(this.rs.next());
        rsmd = this.pstmt.getMetaData();
        assertEquals(testCase, "id", rsmd.getColumnName(1));
    } while (useSPS = !useSPS);
}
 
Example 13
Project: parabuild-ci   File: TestBug808460.java   View Source Code Vote up 5 votes
public void test() throws Exception {

        Connection conn = newConnection();
        Statement  stmt = conn.createStatement();

        stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS");
        conn.close();

        conn = newConnection();
        stmt = conn.createStatement();

        stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS");
        conn.close();
    }
 
Example 14
Project: spr   File: SqlSelects.java   View Source Code Vote up 5 votes
public static List<ProductoPresupuestoDestinatario> selectAllProductosDestinatarios(String condition) throws SQLException{
 	 Connection conect=ConnectionConfiguration.conectar();
 String query = " select * from producto_presupuesto_destinatario "+condition;
 Statement statement = null;
 ResultSet rs=null;
 List<ProductoPresupuestoDestinatario> objetos = new ArrayList<ProductoPresupuestoDestinatario>();   		 

try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);
	while(rs.next()){
		ProductoPresupuestoDestinatario objeto = new ProductoPresupuestoDestinatario();
		
		objeto.setId(rs.getInt("id"));
		objeto.setDepartamento(rs.getInt("departamento"));
		objeto.setCantidad(rs.getDouble("cantidad"));
		objeto.setCatalogo_destinatario (rs.getInt("catalogo_destinatario"));
		objeto.setProducto(rs.getShort("producto"));
		objeto.setProyecto(rs.getShort("proyecto"));
		objeto.setSubprograma(rs.getShort("subprograma"));
		objeto.setPrograma(rs.getShort("programa"));
		objeto.setTipo_presupuesto(rs.getShort("tipo_presupuesto"));
		objeto.setEntidad(rs.getShort("entidad"));
		objeto.setNivel(rs.getShort("nivel"));
		objeto.setFechaActualizacion(rs.getTimestamp("fecha_actualizacion"));
		if (rs.getString("descripcion") != null) 
			objeto.setDescripcion((rs.getString("descripcion")));
		objeto.setBorrado(rs.getBoolean("borrado"));
		
		objetos.add(objeto);
	}
}
catch (SQLException e) {e.printStackTrace();}
finally{
	if (statement != null) {statement.close();}
	if (conect != null) {conect.close();}
}
return objetos;
 }
 
Example 15
Project: aliyun-maxcompute-data-collectors   File: DirectMySQLExportTest.java   View Source Code Vote up 5 votes
private void verifyTableColumnContents(Connection connection,
  String table, String column, ColumnGenerator gen)
    throws IOException, SQLException {
  Statement st = connection.createStatement();

  // create a target database table.
  assertTrue(st.execute("SELECT " + column + " FROM " + table));
  ResultSet rs = st.getResultSet();

  for (int row = 0; rs.next(); ++row) {
    assertEquals(gen.getVerifyText(row), rs.getString(1));
  }
}
 
Example 16
Project: DBus   File: CatalogQueryManager.java   View Source Code Vote up 4 votes
@Override
public String[] listDatabases() {
  Connection c = null;
  Statement s = null;
  ResultSet rs = null;
  List<String> databases = new ArrayList<String>();
  try {
    c = getConnection();
    s = c.createStatement();
    rs = s.executeQuery(getListDatabasesQuery());
    while (rs.next()) {
      databases.add(rs.getString(1));
    }
    c.commit();
  } catch (SQLException sqle) {
    try {
      if (c != null) {
        c.rollback();
      }
    } catch (SQLException ce) {
        LOG.warn("Failed to rollback transaction", ce);
    }
    LOG.warn("Failed to list databases", sqle);
    throw new RuntimeException(sqle);
  }catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException re) {
        LOG.warn("Failed to close resultset", re);
      }
    }
    if (s != null) {
      try {
        s.close();
      } catch (SQLException se) {
        LOG.warn("Failed to close statement", se);
      }
    }
  }

  return databases.toArray(new String[databases.size()]);
}
 
Example 17
Project: ProyectoPacientes   File: StatementRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#5874, timezone correction goes in wrong 'direction' (when useTimezone=true and server timezone differs from client timezone).
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug5874() throws Exception {
    TimeZone defaultTimezone = TimeZone.getDefault();

    try {
        String clientTimezoneName = "America/Los_Angeles";
        String serverTimezoneName = "America/Chicago";

        TimeZone.setDefault(TimeZone.getTimeZone(clientTimezoneName));

        long clientTimezoneOffsetMillis = TimeZone.getDefault().getRawOffset();
        long serverTimezoneOffsetMillis = TimeZone.getTimeZone(serverTimezoneName).getRawOffset();

        long offsetDifference = clientTimezoneOffsetMillis - serverTimezoneOffsetMillis;

        SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

        long pointInTime = timestampFormat.parse("2004-10-04 09:19:00").getTime();

        Properties props = new Properties();
        props.put("useTimezone", "true");
        props.put("serverTimezone", serverTimezoneName);
        props.put("cacheDefaultTimezone", "false");

        Connection tzConn = getConnectionWithProps(props);
        Statement tzStmt = tzConn.createStatement();
        createTable("testBug5874", "(tstamp DATETIME, t TIME)");

        PreparedStatement tsPstmt = tzConn.prepareStatement("INSERT INTO testBug5874 VALUES (?, ?)");

        tsPstmt.setTimestamp(1, new Timestamp(pointInTime));
        tsPstmt.setTime(2, new Time(pointInTime));
        tsPstmt.executeUpdate();

        this.rs = tzStmt.executeQuery("SELECT * from testBug5874");

        while (this.rs.next()) { // Driver now converts/checks DATE/TIME/TIMESTAMP/DATETIME types when calling getString()...
            String retrTimestampString = new String(this.rs.getBytes(1));
            Timestamp retrTimestamp = this.rs.getTimestamp(1);

            java.util.Date timestampOnServer = timestampFormat.parse(retrTimestampString);

            long retrievedOffsetForTimestamp = retrTimestamp.getTime() - timestampOnServer.getTime();

            assertEquals("Original timestamp and timestamp retrieved using client timezone are not the same", offsetDifference,
                    retrievedOffsetForTimestamp);

            String retrTimeString = new String(this.rs.getBytes(2));
            Time retrTime = this.rs.getTime(2);

            java.util.Date timeOnServerAsDate = timeFormat.parse(retrTimeString);
            Time timeOnServer = new Time(timeOnServerAsDate.getTime());

            long retrievedOffsetForTime = retrTime.getTime() - timeOnServer.getTime();

            assertEquals("Original time and time retrieved using client timezone are not the same", offsetDifference, retrievedOffsetForTime);
        }

        tzConn.close();
    } finally {
        TimeZone.setDefault(defaultTimezone);
    }
}
 
Example 18
Project: OSWf-OSWorkflow-fork   File: JDBCTest.java   View Source Code Vote up 4 votes
@After
public void after() throws Exception {
    Connection connection = jdbcPropertySet.getConnection();
    Statement statement = connection.createStatement();
    statement.execute("DROP TABLE OS_PROPERTYENTRY");
}
 
Example 19
Project: blanco-sfdc-jdbc-driver   File: BlancoSfdcJdbcStatement3Test.java   View Source Code Vote up 4 votes
public void test004() throws Exception {
	if (BlancoSfdcJdbcTestConstants.isTestWithSfdc() == false)
		return;

	Class.forName("blanco.sfdc.jdbc.driver.BlancoSfdcJdbcDriver");
	try {
		final Properties prop = new Properties();
		final InputStream inStream = new FileInputStream("soqlro.properties");
		prop.load(new BufferedInputStream(inStream));
		inStream.close();

		final String url = prop.getProperty("url",
				"jdbc:blanco:sfdc:soqlro://login.salesforce.com/services/Soap/u/40.0");
		final String user = prop.getProperty("user", "NoUserSpesified");
		final String pass = prop.getProperty("password", "NoPassSpecified");

		final Connection conn = DriverManager.getConnection(url, user, pass);

		final Statement stmt = conn.createStatement();
		final String sql = "select Name from Account";
		final ResultSet rs = stmt.executeQuery(sql);

		{
			final AbstractBlancoGenericJdbcStatement stmt2 = (AbstractBlancoGenericJdbcStatement) stmt;
			final String tableName = "GMETA_COLUMNS_" + stmt2.getGlobalUniqueKey();
			final AbstractBlancoGenericJdbcConnection conn2 = (AbstractBlancoGenericJdbcConnection) stmt2
					.getConnection();
			final ResultSet rs2 = conn2.getCacheConnection().createStatement()
					.executeQuery("select * from " + tableName);
			final ResultSetMetaData rsmd2 = rs2.getMetaData();
			for (; rs2.next();) {
				for (int colNum2 = 1; colNum2 <= rs2.getMetaData().getColumnCount(); colNum2++) {
					rsmd2.getColumnName(colNum2);
					rs2.getString(colNum2);
				}
			}
		}

		rs.next();
		final ResultSetMetaData rsmd = rs.getMetaData();
		for (int indexCol = 1; indexCol <= rsmd.getColumnCount(); indexCol++) {
			String result = "";
			result += rsmd.getColumnName(indexCol) + " (" + rsmd.getColumnTypeName(indexCol) + "): "
					+ rsmd.getColumnType(indexCol);
			// System.out.println(result);
		}

		rs.close();
		stmt.close();
		conn.close();
	} catch (Exception ex) {
		fail();
	}
}
 
Example 20
Project: OpenDiabetes   File: JDBCBench.java   View Source Code Vote up 2 votes
void checkSums(Connection conn) throws SQLException {

        Statement st1 = null;
        ResultSet rs  = null;
        int       bbalancesum;
        int       tbalancesum;
        int       abalancesum;
        int       deltasum;

        try {
            st1 = conn.createStatement();
            rs  = st1.executeQuery("select sum(bbalance) from branches");

            rs.next();

            bbalancesum = rs.getInt(1);

            rs.close();

            rs = st1.executeQuery("select sum(tbalance) from tellers");

            rs.next();

            tbalancesum = rs.getInt(1);

            rs.close();

            rs = st1.executeQuery("select sum(abalance) from accounts");

            rs.next();

            abalancesum = rs.getInt(1);

            rs.close();

            rs = st1.executeQuery("select sum(delta) from history");

            rs.next();

            deltasum = rs.getInt(1);

            rs.close();

            rs = null;

            st1.close();

            st1 = null;

            if (abalancesum != bbalancesum || bbalancesum != tbalancesum
                    || tbalancesum != deltasum) {
                System.out.println("sums don't match!");
            } else {
                System.out.println("sums match!");
            }

            System.out.println("A " + abalancesum + " B " + bbalancesum
                               + " T " + tbalancesum + " H " + deltasum);
        } finally {
            if (st1 != null) {
                st1.close();
            }
        }
    }