I'm trying to update one row in my db using Query but I have no idea why it doesn't work.
I use this method:
#Override
public void updateImage(String avatar, int employeeId) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
Transaction transaction = null;
Query query = session.createQuery("UPDATE vt_employee SET emp_avatar=? WHERE id_employee=?");
query.setString(0, avatar);
query.setInteger(1, employeeId);
transaction = session.beginTransaction();
query.executeUpdate();
transaction.commit();
} catch (Exception e) {
e.getStackTrace();
} finally {
session.clear();
}
}
My values avatar and employeeId of course are not null or empty I checked it by display in console. My table in db is vt_employee and fields like emp_avatar and id_employee exist.
I checked in which place is problem and problem is in createQuery, if I tried to display arguments before session.createQuery then they displayed in console but after this one line they don't.
Could someone help to solve this problem?
Can you try with this.
public void updateImage(String avatar, int employeeId) {
String hql = "UPDATE vt_employee set emp_avatar =:avatar WHERE id_employee =:employeeId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("avatar",avatar);
query.setParameter("employeeId",employeeId);
int i = query.executeUpdate();
if (i > 0) {
System.Out.println("Updated..") ;
}
}
Related
I have two classes, from which I want one int number (first code) inserted into a database. The only thing I found so far is with a prepared statement, but I want the int from "freeparking" inserted into the database (second code) every hour. I have prepared a sleep thread already, which lets my second code initiate every full hour. But I am not sure how to insert the integer with my database. Thanks for your help in advance!
private void setFreieparkplätze(int freeparking) {
this.freeparking = freeparking;
}
int freeparking = vehiclenumber.getParking();
}
static Connection connection = null;
static String databaseName = "";
static String url = "jdbc:mysql://localhost:3306/tiefgarage?autoReconnect=true&useSSL=false" + databaseName;
static String username = "";
static String password = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, username, password);
**PreparedStatement ps = connection.prepareStatement("INSERT Into parkinglot(Numbers) VALUES (?)");** // ???
int status = ps.executeUpdate();
if (status != 0) {
System.out.println("Database connected");
System.out.println("Record was inserted");
}
I repeat my comment as answer to make it visible to anyone.
The query to add an integer in a db shoould be like:
INSERT Into parkinglot(Numbers) VALUES ("+ getFreeparking() +");
Note that Numbers (table column) has to be integer type and getFreeparking() is just a getter for freeparking int variable.
I have a problem with renaming a specific value in a column in mySQL Database. At first i thought i could just use 'AS' to rename, but i'm actually trying to rename a value in a column. My column is named FoundLost. In this column I Store values '0' and '1'. '0' is Found and '1' is Lost.
The reason I need to rename this values is because I use the data from this database to create a pieChart. with the function .getName it gives the names '0' and '1'.
I was hoping someone could help me out!
The class with the query is the code below:
public static ObservableList getPChartFoundLost() {
String query = "SELECT FoundLost, concat(round(count(FoundLost) *100 / (SELECT count(FoundLost) FROM Luggage))) AS percent FROM Luggage GROUP BY FoundLost";
ObservableList FoundLost = FXCollections.observableArrayList();
Connection connection = DatabaseUtils.connect();
if (connection != null) {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
FoundLost.add(new PieChart.Data(resultSet.getString("FoundLost"), resultSet.getInt("percent")));
}
resultSet.close();
statement.close();
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
}
DatabaseUtils.disconnect(connection);
}
return FoundLost;
}
Controller:
public void clickPChartFoundLost(ActionEvent event) {
//PieChart
ObservableList FoundLost = StatisticsUtils.getPChartFoundLost();
pieChart.setVisible(true);
pieChart.setData(FoundLost);
pieChart.setTitle("Found and Lost luggage");
for (final PieChart.Data data : pieChart.getData()) {
data.getNode().addEventHandler(MouseEvent.ANY,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
//Label vullen met data van Observable list uit Database
pieChartValueLable.setText(String.valueOf(data.getName()) + ": "
+ String.valueOf(data.getPieValue()) + "%");
}
});
}
}
Thanks!!
In your query, try this as your first column instead of just FoundLost. It translates your 0 and 1 values to meaningful strings for your chart. The rest of your query can stay the same.
IF(FoundLost = 0,'Found','Lost') AS FoundLost
I'm having trouble convert this String sql results into int. Can you guys tell how to accomplish this.
I'm doing this because I need this value set in to a JLabel that shows attendance count.
I've tried to search for the answer here, but I couldn't find it. Please can you guys help me with this problem?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
This is what I need to accomplish.
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
Or is there another way to accomplish this without doing this way?
Thanks.
get ResultSet.getInt(1):
int id = rst.getInt(1);
You could use ResultSet.getInt() method. It takes either a column index or a column name. Here's an example from Oracle.
In your case you would need the one which takes the index (note that index starts with 1, not 0).
As suggested earlier, try using .getInt() method.
Moreover, I would use PreparedStatement. It's important to use PreparedStatement, because it allows database to cache your queries.
Also, always close your Connection and ResultSet after using them.
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}
I am trying to run the following query in my java web application:
SELECT platform AS "Platform" FROM edb.cases
The web-app is working fine and is able to execute all queries however whenever I use an alias (through 'AS'), the resultant data-set gives me a null value for the alias. In fact, despite using an alias for the column 'platform' in the above query, the resultant data-set has a null value for the key 'Platform' but gives me the correct value for the key 'platform' (which is the original name of the column).
Now the actual sql statement which I need to execute is a bit more complex with select statements and left joins on the same table twice using aliases, like so:
SELECT numOne.platform , numTwo.platform AS 'PlatformTwo' FROM edb.cases LEFT JOIN
edb.platform as numOne ON (numOne.rank = cases.platform) LEFT JOIN edb.platform as numTwo ON
(numTwo.rank = cases.highestPlatform) WHERE cases.index = 1000
The problem is that the resultant data-set contains the correct value for the key 'platform' (for numOne table) but the keys 'PlatformOne' and 'PlatformTwo' DO NOT EXIST. The aliases are not working!
I have tried both the statements in MySql workbench and they work fine.
Please do not hesitate to ask for more information.
EDIT:
The code that prepares the query and sends it to the database:
public static List<Map<String, Object>> executeQuery(final String query,
Map<Integer, Object> data) {
List<Map<String, Object>> result = null;
try {
Connection conn = createConnection();
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement(query);
if(data != null) {
pstmt = createPreparedStatement(pstmt, data);
}
System.out.println(pstmt.toString());
//The GET_CASE_FOR_INDEX query uses the executequery function in the else block:
if((pstmt.toString().indexOf("INSERT") >= 0) || (pstmt.toString().indexOf("UPDATE") >= 0)) {
pstmt.executeUpdate();
} else {
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
result = new ArrayList<Map<String, Object>>();
/*
* Get the next row of the ResultSet 'rs' and insert a Map of the Column/Value pair
* into the ArrayList of Maps 'result'
*/
while(rs.next()) {
Map<String, Object> row = new HashMap<String, Object>(columns);
for(int i=1; i <= columns; i++) {
try {
row.put(md.getColumnName(i), rs.getObject(i));
} catch(Exception e) {
System.out.println(md.getColumnName(i));
System.out.println(row);
e.printStackTrace();
}
}
result.add(row);
}
}
destroyConnection(conn);
pstmt.close();
} catch(SQLException e) {
//TODO
e.printStackTrace();
}
return result;
}
The function creating the prepared statement:
//creates a prepared statement by checking the type of the value that needs to be set.
private static PreparedStatement createPreparedStatement(
PreparedStatement pstmt, Map<Integer, Object> data) {
try {
for(Integer key : data.keySet()) {
Object value = data.get(key);
System.out.println(key);
if(data.get(key).equals(Types.NULL)) {
pstmt.setNull(key, Types.INTEGER);
} else if(value.getClass().equals(Integer.class)) {
pstmt.setInt(key, (Integer) value);
} else if(value.getClass().equals(String.class)) {
pstmt.setString(key, (String) value);
} else if(value.getClass().equals(Date.class)) {
pstmt.setDate(key, (Date) value);
} else if(value.getClass().equals(Timestamp.class)) {
pstmt.setTimestamp(key, (Timestamp) value);
}
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pstmt;
}
And the code snippet which uses the executeQuery function to execute the query and sends it to the web template:
Map<Integer, Object> data_details = new HashMap<Integer, Object>();
data_details.put(1, parameter_ID);
List<Map<String, Object>> details = DBUtility.executeQuery(DBQuery.GET_CASE_FOR_INDEX, data_details);
webContext.setVariable("details", details);//This is where the template variable is being set
System.out.println(details);
The GET_CASE_FOR_INDEX query is :
SELECT numOne.platform , numTwo.platform AS 'PlatformTwo' FROM edb.cases LEFT JOIN
edb.platform as numOne ON (numOne.rank = cases.platform) LEFT JOIN edb.platform as numTwo ON
(numTwo.rank = cases.highestPlatform) WHERE cases.index = ?
When I print the details hash map (which is the result data-set) the key PlatformTwo is entirely absent!
You are using the .getColumnName method of ResultSetMetaData, which returns the name of the underlying column (if available). .getColumnLabel will return the column alias as defined by SELECT ... AS ....
To illustrate, the following Java code
PreparedStatement ps = conn.prepareStatement(
"SELECT platform AS Platypus FROM cases");
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(String.format(
".getColumnName returns \"%s\"",
rsmd.getColumnName(1)));
System.out.println(String.format(
".getColumnLabel returns \"%s\"",
rsmd.getColumnLabel(1)));
returns
.getColumnName returns "platform"
.getColumnLabel returns "Platypus"
And once again I have found an issue that I don't know how to fight with. Let's assume we have the following testing code:
private static final String CREATE_TEMPORARY_TABLE =
"CREATE TEMPORARY TABLE T1 (\n" +
"\tA FLOAT(4, 1),\n" +
"\tB FLOAT(5, 2),\n" +
"\tC FLOAT,\n" +
"\tD INTEGER\n" +
") ENGINE = MEMORY;";
private final String[] SHOW_TABLE_TYPES = new String[] {
//"TABLE",
"VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
};
private void createTemporaryTable(Connection connection) throws SQLException {
final PreparedStatement statement = connection.prepareStatement(CREATE_TEMPORARY_TABLE);
statement.execute();
statement.close();
}
private void showTables(Connection connection) throws SQLException {
final ResultSet set = connection.getMetaData().getTables(null, null, null, SHOW_TABLE_TYPES);
while ( set.next() ) {
out.println(format("%s %s %s %s %s",
set.getString("TABLE_CAT"),
set.getString("TABLE_SCHEM"),
set.getString("TABLE_NAME"),
set.getString("TABLE_TYPE"),
set.getString("REMARKS")
));
}
set.close();
}
#Override
public void test(Connection connection) throws SQLException {
createTemporaryTable(connection);
showTables(connection);
}
Expected result is writing the T1 table meta data into the out stream. But nothing happens, and it seems that getTables() does not take into account the temporary tables. Don't know how I can resolve it... Is a work-around there? Your help is really very appreciated. Thanks a lot in advance.
MySQL sometimes does not provide support even for stupid things. There is no solution for the issue. Closed.