Java Code Examples for com.mysql.jdbc.PreparedStatement

The following are top voted examples for showing how to use com.mysql.jdbc.PreparedStatement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: the-vigilantes   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 2
Project: OpenVertretung   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 3
Project: ProyectoPacientes   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 4
Project: BibliotecaPS   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 5
Project: mot-public-api   File: VehicleReadDaoTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getVehiclebyIdAndVersion_WithNoMatches_ReturnsNull() throws SQLException {

    final int vehicleId = 890321;
    final int version = 23000;

    PreparedStatement mockStatement2 = mock(PreparedStatement.class);

    when(mockStatement2.executeQuery()).thenReturn(mockResultSet);

    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleByIdAndVersion))
            .thenReturn(mockStatement);
    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleHistByIdAndVersion))
            .thenReturn(mockStatement2);

    Vehicle actual = vehicleReadReadDao.getVehicleByIdAndVersion(vehicleId, version);

    verify(mockStatement).setObject(1, vehicleId);
    verify(mockStatement).setObject(2, version);
    verify(mockStatement2).setObject(1, vehicleId);
    verify(mockStatement2).setObject(2, version);
    assertThat(actual, nullValue());
}
 
Example 6
Project: mot-public-api   File: VehicleReadDaoTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getVehiclebyIdAndVersion_WithMatches_ReturnsVehicle() throws SQLException {

    final int vehicleId = 890321;
    final int version = 23000;

    PreparedStatement mockStatement2 = mock(PreparedStatement.class);
    ResultSet resultSet2 = mock(ResultSet.class);
    ResultSetMockHelper.initialize(resultSet2);

    when(resultSet2.next()).thenReturn(true);
    when(mockStatement2.executeQuery()).thenReturn(resultSet2);

    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleByIdAndVersion))
            .thenReturn(mockStatement2);
    when(mockConnection.prepareStatement(argThat(not(equalTo(VehicleReadSql.queryGetVehicleByIdAndVersion)))))
            .thenReturn(mockStatement);

    Vehicle actual = vehicleReadReadDao.getVehicleByIdAndVersion(vehicleId, version);

    verify(mockStatement2).setObject(1, vehicleId);
    verify(mockStatement2).setObject(2, version);
    assertThat(actual, notNullValue());
}
 
Example 7
Project: mot-public-api   File: VehicleReadDaoTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = InternalException.class)
public void getVehiclebyIdAndVersion_ExecuteThrows_ThrowsInternalException() throws SQLException, InternalException {

    final int vehicleId = 890321;
    final int version = 23000;

    PreparedStatement mockStatement2 = mock(PreparedStatement.class);
    ResultSet resultSet2 = mock(ResultSet.class);
    ResultSetMockHelper.initialize(resultSet2);

    when(mockStatement2.executeQuery()).thenThrow(new SQLException(""));

    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleByIdAndVersion))
            .thenReturn(mockStatement2);

    vehicleReadReadDao.getVehicleByIdAndVersion(vehicleId, version);
}
 
Example 8
Project: mot-public-api   File: VehicleReadDaoTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = InternalException.class)
public void getVehicleByIdAndVersion_NoCurrent_GoesToHistory_HistoryThrows_ThrowsInternalException()
        throws SQLException, InternalException {

    final int vehicleId = 890321;
    final int version = 23000;

    PreparedStatement mockStatement2 = mock(PreparedStatement.class);

    when(mockStatement2.executeQuery()).thenThrow(new SQLException(""));

    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleHistByIdAndVersion))
            .thenReturn(mockStatement2);
    when(mockConnection
            .prepareStatement(argThat(not(equalTo(VehicleReadSql.queryGetVehicleHistByIdAndVersion)))))
            .thenReturn(mockStatement);

    vehicleReadReadDao.getVehicleByIdAndVersion(vehicleId, version);
}
 
Example 9
Project: sierra   File: MySqlUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIterate() throws SQLException {
	String testSql = "SELECT * FROM Sequence";

	JdbcDatabase db = spy(new JdbcDatabase(null, null, null));
	Connection conn = mock(Connection.class);
	doReturn(conn).when(db).getConnection();
	PreparedStatement stmt = mock(PreparedStatement.class);
	ResultSet thers = mock(ResultSet.class);
	when(thers.next()).thenReturn(true, true, true, false);
	when(stmt.executeQuery()).thenReturn(thers);
	when(conn.prepareStatement(any(String.class))).thenReturn(stmt);

	List<Integer> result = db.iterate(testSql, rs -> 17);
	verify(conn, times(1)).prepareStatement(testSql);
	assertEquals(Arrays.asList(new Integer[] {17, 17, 17}), result);
}
 
Example 10
Project: sierra   File: MySqlUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSelectAllExceptionThrowed() throws SQLException {
	String testSql = "SELECT * FROM Isolate";

	JdbcDatabase db = spy(new JdbcDatabase(null, null, null));
	Connection conn = mock(Connection.class);
	doReturn(conn).when(db).getConnection();
	PreparedStatement stmt = mock(PreparedStatement.class);
	when(conn.prepareStatement(any(String.class))).thenReturn(stmt);

	try {
		db.selectAll(testSql, rs -> {
			throw new RuntimeException();
		});
		assertTrue(false);
	}
	catch (RuntimeException e) {
		// pass
	}
	verify(conn, times(1)).prepareStatement(testSql);
}
 
Example 11
Project: scada   File: MeetManagerDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String check(String id){
	Connection conn=null;
	String sql=null;
	String sql_1=null;
	try{
		conn=getConnection();
		
           sql="SELECT `meet_id` FROM scada.meet_manager WHERE meet_id="+id;
        
        PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
        
        ResultSet rs=ps.executeQuery();
        
        while(rs.next()){
        	sql_1=rs.getString("meet_id");
        }
        
        conn.close();
        
        return sql_1;
        
	}catch(Exception e){
		e.printStackTrace();
	}
	
	return sql_1;
}
 
Example 12
Project: Geometry-wars   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 13
Project: TPKB   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 14
Project: cloudera-cli-scripts   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests Util.isJdbcInterface()
 * 
 * @throws Exception
 */
public void testIsJdbcInterface() throws Exception {
    // Classes directly or indirectly implementing JDBC interfaces.
    assertTrue(Util.isJdbcInterface(PreparedStatement.class));
    assertTrue(Util.isJdbcInterface(StatementImpl.class));
    assertTrue(Util.isJdbcInterface(Statement.class));
    assertTrue(Util.isJdbcInterface(ResultSetImpl.class));
    Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { Statement.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return null;
        }
    });
    assertTrue(Util.isJdbcInterface(s.getClass()));

    // Classes not implementing JDBC interfaces.
    assertFalse(Util.isJdbcInterface(Util.class));
    assertFalse(Util.isJdbcInterface(UtilsTest.class));

}
 
Example 15
Project: mapleLemon   File: AdminCommand.java   Source Code and License 6 votes vote down vote up
@Override
public int execute(MapleClient c, String[] splitted) {
    if (splitted.length < 2) {
        c.getPlayer().dropMessage(0, splitted[0] + " <SQL命令>");
        return 0;
    }
    try {
        Connection con = (Connection) DatabaseConnection.getConnection();
        PreparedStatement ps = (PreparedStatement) con.prepareStatement(StringUtil.joinStringFrom(splitted, 1));
        ps.executeUpdate();
        ps.close();
    } catch (SQLException e) {
        c.getPlayer().dropMessage(0, "执行SQL命令失败");
        return 0;
    }
    return 1;
}
 
Example 16
Project: tradedirectionprediction   File: MySQLDatabase.java   Source Code and License 6 votes vote down vote up
@Override
public boolean checkIfRowExists(int n, double gamma, double C,int total_rows,int training_rows,int run){
    try{
        String sql = "SELECT id FROM "+this.tablename+" WHERE gamma = ? AND C = ? AND total_rows = ? AND training_rows = ? AND run = ?";
        PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
        preparedStatement.setDouble(1, gamma);
        preparedStatement.setDouble(2, C);
        preparedStatement.setInt(3, total_rows);
        preparedStatement.setInt(4, training_rows);
        preparedStatement.setInt(5, run);
        ResultSet rs = (ResultSet) preparedStatement.executeQuery();
        return rs.next();
    }catch(SQLException ex){
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());  
        System.exit(1);
    }
    return false;
}
 
Example 17
Project: tradedirectionprediction   File: MySQLDatabase.java   Source Code and License 6 votes vote down vote up
@Override
public void write(int n,double gamma, double C,int total_rows,int training_rows,int run,int correct_nbr,double correct_prc) {
    try {
        String sql = "INSERT INTO "+this.tablename+" (gamma,C,total_rows,training_rows,run,correct_nbr,correct_prc) VALUES (?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
        preparedStatement.setDouble(1, gamma);
        preparedStatement.setDouble(2, C);
        preparedStatement.setInt(3, total_rows);
        preparedStatement.setInt(4, training_rows);
        preparedStatement.setInt(5, run);
        preparedStatement.setInt(6, correct_nbr);
        preparedStatement.setDouble(7, correct_prc);
        preparedStatement.execute();
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        System.exit(1);
    }            
}
 
Example 18
Project: Excitement-TDMLEDA   File: SyntacticAbstractOfflineFuncClassifier.java   Source Code and License 6 votes vote down vote up
public void setRanksByPatternLocation(String patternKind , String rankQuery, String select_func, int classifierId) throws SQLException
{
	int patternType =getPatternType(patternKind);
	int pattern_count = getDifferntPatternsCount(patternType , select_func);
	if (pattern_count == 0)
		throw new SQLException("No rule pattern was found in the database");
	float pattern_mul = (1/(float)(pattern_count));

	String query =  " insert into rulesranks(ruleId,classifierId,rank) " + rankQuery;
			
	logger.info("classifierId= " + classifierId);
	logger.info("pattern_mul= " + pattern_mul);
	logger.info("patternType= " + patternType);
	
	Connection conn = m_retrivalTool.getMySqlConnection();
	PreparedStatement cs = (PreparedStatement) conn.prepareStatement(query);
	cs.setInt(1, classifierId);
	cs.setFloat(2, pattern_mul);
	cs.setInt(3, patternType);		

	cs.execute();
	RetrievalTool.closeConnection();			
}
 
Example 19
Project: Excitement-TDMLEDA   File: SyntacticAbstractOfflineFuncClassifier.java   Source Code and License 6 votes vote down vote up
/**
 * Calls the DB and return a number
 * @param parameter1	-- what value to put as a parameter to the query(if null- won't use it) 
 * @param query			-- query to run, the return value will be in column "num"
 * @return	the res of the query
 * @throws SQLException
 */
private int getNumFromDB(String parameter1, String query, String numColumnName) throws SQLException {
	Connection conn = m_retrivalTool.getMySqlConnection();
	PreparedStatement cs = (PreparedStatement) conn.prepareStatement(query);
	
	if (parameter1 != null)
	{
		cs.setString(1, parameter1);
	}
	ResultSet rs = cs.executeQuery();
	RetrievalTool.closeConnection();
	while (rs.next())
	{
		return rs.getInt(numColumnName);
	}
	
	return (-1);
}
 
Example 20
Project: Excitement-TDMLEDA   File: InsertionTool.java   Source Code and License 6 votes vote down vote up
public HashSet<Integer> getDoneBeforeCrashForType(int extractionMethodID) throws SQLException {

		HashSet<Integer> results = new HashSet<Integer>();
		java.sql.Connection conn = getNewtMySqlConnection();
		PreparedStatement cs = (PreparedStatement) conn.prepareStatement("SELECT ruleSourceId FROM .rules where ruletype = ? group by ruleSourceId;");
		
		cs.setInt(1, extractionMethodID);
		
		ResultSet rs = cs.executeQuery();
		
		while (rs.next())
		{
			results.add(rs.getInt(1));
		}
		conn.close();
		
		return results;
	}
 
Example 21
Project: DAAExample   File: DatabaseQueryUnitTest.java   Source Code and License 6 votes vote down vote up
/**
 * Configures the mocks and enables the verification.
 * 
 * @throws Exception if an error happens while configuring the mocks.
 */
@Before
public void setUp() throws Exception {
	datasource = createMock(DataSource.class);
	connection = createMock(Connection.class);
	statement = createNiceMock(PreparedStatement.class);
	result = createMock(ResultSet.class);
	
	expect(datasource.getConnection())
		.andReturn(connection);
	expect(connection.prepareStatement(anyString()))
		.andReturn(statement)
		.anyTimes(); // statement is optional
	expect(statement.executeQuery())
		.andReturn(result)
		.anyTimes(); // executeQuery is optional
	statement.close();
	connection.close();
	
	verify = true;
}
 
Example 22
Project: the-vigilantes   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 23
Project: OpenVertretung   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 24
Project: lams   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 25
Project: ProyectoPacientes   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 26
Project: BibliotecaPS   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 27
Project: Lucid2.0   File: AdminCommand.java   Source Code and License 5 votes vote down vote up
@Override
public int execute(MapleClient c, String[] splitted) {
    try {
        Connection con = (Connection) DatabaseConnection.getConnection();
        PreparedStatement ps = (PreparedStatement) con.prepareStatement(StringUtil.joinStringFrom(splitted, 1));
        ps.executeUpdate();
    } catch (SQLException e) {
        c.getPlayer().dropMessage(0, "Failed to execute SQL command.");
        return 0;
    }
    return 1;
}
 
Example 28
Project: mot-public-api   File: VehicleReadDaoTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getVehicleByIdAndVersion_NoCurrent_GoesToHistory() throws SQLException {

    final int vehicleId = 890321;
    final int version = 23000;

    PreparedStatement mockStatement2 = mock(PreparedStatement.class);
    ResultSet resultSet2 = mock(ResultSet.class);
    ResultSetMockHelper.initialize(resultSet2);

    when(resultSet2.next()).thenReturn(true);

    when(mockStatement2.executeQuery()).thenReturn(resultSet2);

    when(mockConnection.prepareStatement(VehicleReadSql.queryGetVehicleHistByIdAndVersion))
            .thenReturn(mockStatement2);
    when(mockConnection
            .prepareStatement(argThat(not(equalTo(VehicleReadSql.queryGetVehicleHistByIdAndVersion)))))
            .thenReturn(mockStatement);

    Vehicle actual = vehicleReadReadDao.getVehicleByIdAndVersion(vehicleId, version);

    verify(mockStatement).setObject(1, vehicleId);
    verify(mockStatement).setObject(2, version);
    verify(mockStatement2).setObject(1, vehicleId);
    verify(mockStatement2).setObject(2, version);
    assertThat(actual, notNullValue());
}
 
Example 29
Project: sierra   File: MySqlUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSelectAll() throws SQLException {
	String testSql = "SELECT * FROM Sequence";

	JdbcDatabase db = spy(new JdbcDatabase(null, null, null));
	Connection conn = mock(Connection.class);
	doReturn(conn).when(db).getConnection();
	PreparedStatement stmt = mock(PreparedStatement.class);
	when(conn.prepareStatement(any(String.class))).thenReturn(stmt);

	db.selectAll(testSql, rs -> null);
	verify(conn, times(1)).prepareStatement(testSql);
}
 
Example 30
Project: sierra   File: MySqlUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIterateMap() throws SQLException {
	String testSql = "SELECT * FROM Sequence";

	JdbcDatabase db = spy(new JdbcDatabase(null, null, null));
	Connection conn = mock(Connection.class);
	doReturn(conn).when(db).getConnection();
	PreparedStatement stmt = mock(PreparedStatement.class);
	ResultSet thers = mock(ResultSet.class);
	when(thers.next()).thenReturn(true, true, true, false);
	when(thers.getInt(0)).thenReturn(13, 14, 15);
	when(stmt.executeQuery()).thenReturn(thers);
	when(conn.prepareStatement(any(String.class))).thenReturn(stmt);

	Map<String, Integer> result = db.iterateMap(testSql, (rs, map) -> {
		int r = rs.getInt(0);
		map.put("" + r, r);
		return null;
	});
	verify(conn, times(1)).prepareStatement(testSql);
	Map<String, Integer> expected = new HashMap<>();
	expected.put("13", 13);
	expected.put("14", 14);
	expected.put("15", 15);

	assertEquals(expected, result);
}
 
Example 31
Project: sierra   File: MySqlUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPrepareStatement() throws SQLException {
	String testSql = "SELECT 1 FROM Sequence WHERE id=? AND name=?)";
	JdbcDatabase db = new JdbcDatabase(null, null, null);
	Connection conn = mock(Connection.class);
	PreparedStatement stmt = mock(PreparedStatement.class);
	when(conn.prepareStatement(any(String.class))).thenReturn(stmt);

	db.prepareStatement(
		conn, testSql, 146, "test");
	verify(conn, times(1)).prepareStatement(testSql);
	verify(stmt, times(1)).setObject(1, 146);
	verify(stmt, times(1)).setObject(2, "test");
}
 
Example 32
Project: MutualAgriculture   File: GsonTest.java   Source Code and License 5 votes vote down vote up
/**
 * url插入数据库乱码,在这儿获取数据看看是不是url编码问题
 */
@Test
public void getData() {
	Connection connection = DBHelper.getConnection();
	try {
		java.sql.PreparedStatement pstmt = connection
				.prepareStatement("select * from farmland where id=5");
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			String type = rs.getString("type");
			System.out.println(type);
		}
	} catch (SQLException e) {
	}
}
 
Example 33
Project: Mushy   File: AdminCommand.java   Source Code and License 5 votes vote down vote up
@Override
public int execute(MapleClient c, String[] splitted) {
    try {
        Connection con = (Connection) DatabaseConnection.getConnection();
        PreparedStatement ps = (PreparedStatement) con.prepareStatement(StringUtil.joinStringFrom(splitted, 1));
        ps.executeUpdate();
    } catch (SQLException e) {
        c.getPlayer().dropMessage(0, "Failed to execute SQL command.");
        return 0;
    }
    return 1;
}
 
Example 34
Project: scada   File: MeetManagerDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Room> getAllRoom() {
	Connection conn=null;
       try{
       	
       conn=getConnection();
  
       String sql="SELECT * FROM `scada`.`meet_room`;";
       
       PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
       
       ResultSet rs=ps.executeQuery();
       
       List<Room> lr=new ArrayList<Room>();
            
       while(rs.next()){
       	Room r=new Room();
       	r.setMeetroom_id(rs.getInt(1));
       	r.setTime(rs.getString(2));       	
       	r.setUseful(rs.getString(3));      	
       	r.setNum(rs.getInt(4));      
       	lr.add(r);
       	r=null;
       }
       conn.close();  
       conn=null;
       return lr;
             
       }catch(Exception e)
       {
       	e.printStackTrace();
       }
       
	return null;
}
 
Example 35
Project: scada   File: MeetManagerDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void updateAndDelete(int id) {
	
	ActionContext actionContext = ActionContext.getContext();
   	Map<String, Object> session = actionContext.getSession();
   	String select=(String) session.get("select");
   	String message=(String) session.get("message");

   	Connection conn=null;
   	
   	String sql=null;
   	
   	
   	if(!message.equals("")){
   	if(select.equals("id")){
   		try{
   		  			
       		conn=getConnection();
       		     	   
       		sql="UPDATE `scada`.`meet_room` SET `useful`='����' WHERE `meetroom_id`="+"'"+id+"'";

               PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
   		        
       		ps.executeUpdate();
       		    
       	    //MeetManager meetManager=(MeetManager)this.getSessionFactory().openSession().get(MeetManager.class, id);
       		//this.getHibernateTemplate().delete(meetManager);
       		//this.getSessionFactory().openSession().close();
       		conn.close();
       		conn=null;
       		System.out.println(conn);
       		
   		}catch(Exception e){
   			System.out.println(e);		
   	     }
   	}
   		
   }
  }
 
Example 36
Project: scada   File: MeetManagerDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String queryRoomUseful(String id) {
	String sql=null;
	Connection conn=null;
	String useful=null;
	
	try{
		conn=getConnection();
		sql="SELECT `useful` FROM scada.meet_room WHERE `meetroom_id`="+id;
           PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
        
        ResultSet rs=ps.executeQuery();
        
        while(rs.next()){
        	useful=rs.getString("useful");
        }

        conn.close();
        conn=null;
        
        return useful;
	}catch(Exception e){
		
	}
	
	return useful;
}
 
Example 37
Project: scada   File: AchievementDaoImpl.java   Source Code and License 5 votes vote down vote up
public List<MyInformation> getAllinformation(){
	Connection conn=null;
       try{
       	
       conn=getConnection();
  
       String sql="SELECT * FROM `scada`.`information`";
       
       PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
       
       ResultSet rs=ps.executeQuery();
       
       List<MyInformation> lr=new ArrayList<MyInformation>();
            
       while(rs.next()){
       	MyInformation r=new MyInformation();
       	r.setId(rs.getInt("id"));
       	r.setInformation(rs.getString("text"));       	
       	      
       	lr.add(r);
       	r=null;
       }
       conn.close();  
       conn=null;
       return lr;
             
       }catch(Exception e)
       {
       	e.printStackTrace();
       }
       
	return null;
}
 
Example 38
Project: My-Javaweb-Homework   File: MysqlTemplate.java   Source Code and License 5 votes vote down vote up
public ResultSet excute(String sql) {
	ResultSet result = null;
	try {
		Connection connection = cm.getCon();
		connection.setAutoCommit(true);
		PreparedStatement statement = (PreparedStatement) connection
				.prepareStatement(sql);
		result = statement.executeQuery();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 39
Project: Geometry-wars   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 40
Project: TPKB   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 41
Project: cloudera-cli-scripts   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 42
Project: fil_project_mgmt_app_v2   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 43
Project: indoor-tracking   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 44
Project: Excitement-TDMLEDA   File: RetrievalTool.java   Source Code and License 5 votes vote down vote up
/**
 * gets the ID of the classifier from DB
 * @param calssifierName
 * @param insertNewClassifier	- if true: make sure it's the first insert of that name to the DB (if not-throws SQLException)
 * @return ID of the classifier
 * @throws SQLException
 */
public int getClassifierId(String calssifierName, boolean insertNewClassifier) throws SQLException
{
	Connection conn = getMySqlConnection();
	
	int id = (-2);
	
	String query;
	if (insertNewClassifier)	//make sure it's the first, if not -throw exception
	{
		query = "select insertNewClassifier(?) id from dual";
	}
	else
	{
		query = "select getClassifierId(?) id from dual";		
	}
	PreparedStatement cs = (PreparedStatement) conn.prepareStatement(query);
	cs.setString(1, calssifierName);
	ResultSet rs = cs.executeQuery();

	 while (rs.next())
      {
		 id=  rs.getInt("id");
      }

	if (id == (-2))
	{
		 throw new  SQLException("Can't get Id for classifier name: " + calssifierName);
	}
	else if (id == (-1))
	{
		 throw new  SQLException("Classifier Name allreay exists: " + calssifierName);	
	}
	return id;
}
 
Example 45
Project: SMPT42   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 46
Project: ForYou   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 47
Project: group-five   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 48
Project: locaviewer   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 49
Project: locaviewer   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
    if (xmlObject == null) {
        pstmt.setNull(parameterIndex, Types.SQLXML);
    } else {
        // FIXME: Won't work for Non-MYSQL SQLXMLs
        pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML) xmlObject).serializeAsCharacterStream());
    }
}
 
Example 50
Project: manydesigns.cn   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 51
Project: Gladiatus   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 52
Project: Jspad   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 53
Project: Asteria   File: AdminCommand.java   Source Code and License 5 votes vote down vote up
@Override
public int execute(MapleClient c, String[] splitted) {
    try {
        Connection con = (Connection) DatabaseConnection.getConnection();
        PreparedStatement ps = (PreparedStatement) con.prepareStatement(StringUtil.joinStringFrom(splitted, 1));
        ps.executeUpdate();
    } catch (SQLException e) {
        c.getPlayer().dropMessage(0, "Failed to execute SQL command.");
        return 0;
    }
    return 1;
}
 
Example 54
Project: harness   File: DbHelper.java   Source Code and License 5 votes vote down vote up
public void addPerfResults(Test test, UUID batchId, Boolean persist) {

        if(persist){

            connectDb();
            try {

                String sql = "insert into perf(testName,samples,success,failures,minResponseTime,maxResponseTime,avgResponseTime,median,ninetiethPercentile,throughput,batchId,type,createdTime,module,feature,subfeature) values ('" + test.getName() +
                        "','" + test.getSamples() +
                        "','" + test.getSuccess() +
                        "','" + test.getFailure() +
                        "','" + test.getMinResponseTime() +
                        "','" + test.getMaxResponseTime() +
                        "','" + test.getAvgResponseTime() +
                        "','" + test.getMedian() +
                        "','" + test.getNinetiethPercentile() +
                        "','" + test.getThroughput() +
                        "','"  + batchId +
                        "','" + test.getType() +
                        "','" + getCurrentTime() +
                        "','" + test.getModule() +
                        "','" + test.getFeature() +
                        "','" + test.getSubfeature() +
                        "')";
                PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
                ps.execute(sql);
                ps.close();

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }
 
Example 55
Project: Trails   File: JDBC4PreparedStatementHelper.java   Source Code and License 5 votes vote down vote up
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject)
		throws SQLException {
	if (xmlObject == null) {
		pstmt.setNull(parameterIndex, Types.SQLXML);
	} else {
		// FIXME: Won't work for Non-MYSQL SQLXMLs
		pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());	
	}
}
 
Example 56
Project: the-vigilantes   File: JDBC4PreparedStatementHelper.java   Source Code and License 4 votes vote down vote up
static void setRowId(PreparedStatement pstmt, int parameterIndex, RowId x) throws SQLException {
    throw SQLError.createSQLFeatureNotSupportedException();
}
 
Example 57
Project: the-vigilantes   File: JDBC4PreparedStatementHelper.java   Source Code and License 4 votes vote down vote up
static void setNClob(PreparedStatement pstmt, int parameterIndex, Reader reader) throws SQLException {
    pstmt.setNCharacterStream(parameterIndex, reader);
}
 
Example 58
Project: OpenVertretung   File: JDBC4PreparedStatementHelper.java   Source Code and License 4 votes vote down vote up
static void setRowId(PreparedStatement pstmt, int parameterIndex, RowId x) throws SQLException {
    throw SQLError.createSQLFeatureNotSupportedException();
}
 
Example 59
Project: OpenVertretung   File: JDBC4PreparedStatementHelper.java   Source Code and License 4 votes vote down vote up
static void setNClob(PreparedStatement pstmt, int parameterIndex, Reader reader) throws SQLException {
    pstmt.setNCharacterStream(parameterIndex, reader);
}
 
Example 60
Project: lams   File: JDBC4PreparedStatementHelper.java   Source Code and License 4 votes vote down vote up
static void setRowId(PreparedStatement pstmt, int parameterIndex, RowId x) throws SQLException {
    throw SQLError.createSQLFeatureNotSupportedException();
}