I have two jspinners. the one contains an HH:mm format and the other one is a simple number(int) spinner.
when SAVE button clicked I want to update a database table that contains the timeLimit (type time) and attempts (type int) columns. But I dont know how to save a jspinner value to a time type in my database.
String update = "Update qbank SET timeLimit = ? and attempts = ? where qbankID = ?";
preparedStatement = connection.prepareStatement(update);
preparedStatement.setTime(1, spinnerTime.getValue());
i tried the code above but the last part has an error saying spinnerTime.getValue is an object and setTime() requires a Time. How can I convert and object to time? or is there other way to insert a jspinner with time value to my database? any help would be appreciated!
It was just a simple overlooked problem. I just did this code.
Time time; int attempt;
time = (Time) spinnerTime.getValue();
attempt = Integer.parseInt(spinnerAttempt.getValue().toString());
String update = "Update qbank SET timeLimit = ? and attempts = ? where qbankID = ?";
preparedStatement = connection.prepareStatement(update);
preparedStatement.setTime(1, time);
preparedStatement.setInt(2, attempt);
preparedStatement.setInt(3, qbankID);
preparedStatement.executeUpdate();
Related
I use prepared statements to read/write data in my DB (SQLite). In my table INVENTORY, there are records which have null value in the column paleta (the column is defined as VARCHAR in the table). I want to select these records and I tried:
sq = "SELECT * FROM INVENTORY WHERE paleta = ? AND product = ? AND lot = ?";
//...
stm = c.prepareStatement(sq);
stm.setNull(1, java.sql.Types.VARCHAR);
stm.setString(2, "theIdOftheProduct");
stm.setString(3, "theLotOftheProduct");
ResultSet rs = stm.executeQuery();
The above query doesn't return anything.. I removed the paleta = ? and I get the records I want.. How can I define the query like SELECT * FROM INVENTORY WHERE paleta is null etc.. using the query parameters?
What you are trying to do is equivalent to writing SELECT * FROM INVENTORY WHERE paleta = NULL ..., which doesn't work.
Since you are essentially searching for rows having a constant value in the paleta column (which happens to be NULL), you can eliminate the first query parameter and explicitly check for null:
sq = "SELECT * FROM INVENTORY WHERE paleta IS NULL AND product = ? AND lot = ?";
stm = c.prepareStatement(sq);
stm.setString(1, "theIdOftheProduct");
stm.setString(2, "theLotOftheProduct");
I found my answer in https://stackoverflow.com/a/4215618/1052284
You'll have to decide upon an unused value. I simply kept it at '' since I don't have empty values.
sq = "SELECT * FROM INVENTORY WHERE IFNULL(paleta, '') = ? AND product = ? AND lot = ?";
//...
stm = c.prepareStatement(sq);
stm.setString(1, ""); // '' for NULL, otherwise a specific value
stm.setString(2, "theIdOftheProduct");
stm.setString(3, "theLotOftheProduct");
But beware if you many queries, it's VERY slow. I clock in at about 4000 times slower, on average, than queries without IFNULL. ~50ms instead of microseconds.
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.
The code below is a snippet from a back-end REST service I have touched on. I'm wondering how to tell if a timestamp I'm getting is null. I've learned through trial and error that if the timestamp is null in the Postgres database that when I bring it into Java that if its null it will get instantiated as a new DateTime at the current time of operation. What can I do to check get and set nulls dynamically according to model data?
public List<SubscriptionEntityModel> getAllSubscriptions(PagingInfoDomainModel paging) throws Exception {
Database db = new Database();
String stmt = "{call sp_subscriptions_get_all(?, ?)}";
if(AppConfig.data.isDebug) {
logger.debug("Running database operation.. " + stmt);
}
CallableStatement sproc = db.dbEndpoint.prepareCall(stmt);
sproc.setInt(1, paging.pageCurrent);
sproc.setInt(2, paging.pageItemCount);
ResultSet rs = sproc.executeQuery();
List<SubscriptionEntityModel> subscriptions = new ArrayList<SubscriptionEntityModel>();
while(rs.next()) {
SubscriptionEntityModel subscription = new SubscriptionEntityModel();
subscription.subscriptionId = rs.getInt("subscription_id");
subscription.name = rs.getString("name");
subscription.emailAddress = rs.getString("email_address");
subscription.phoneNumber = rs.getString("phone_number");
subscription.organizationId = rs.getInt("organization_id");
subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
subscription.expiredAt = new DateTime(rs.getTimestamp("expired_at"));
subscriptions.add(subscription);
}
sproc.close();
db.destroy();
return subscriptions;
}
Check out ResultSet#wasNull
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull()
Reports whether the last column read had a value of SQL NULL.
Hence you can use it after rs.getTimestamp() to check if the value read was SQL NULL, but note that ResultSet#getTimestamp already returns a null reference if that was the case.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTimestamp(int)
the column value; if the value is SQL NULL, the value returned is null
The problem you're facing is that when you pass a null reference to the constructor of DateTime, it will be interpreted as now.
java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;
will return null if the SQL field is NULL.
The problem is the way you instantiate your DateTime object.
With JodaTime (I give this example as you don't specify the used library), executing the following code creates indeed a DateTime instance with the actual date time :
java.sql.Timestamp timestamp = null;
DateTime dateTime = new DateTime(timestamp);
So to solve your problem, what you could do is checking the returned value by the resultset.
If it is not null, use it to create the DateTime object.
Otherwise don't use it and leave to nullthe DateTime field of the SubscriptionEntityModel you are setting properties.
So instead of doing :
subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
You should do :
java.sql.Timestamp createdAt = rs.getTimestamp("created_at");
if (createdAt != null){
subscription.expiredAt = new DateTime(createdAt);
}
int selectie = toernooienUitvoer.getSelectedRow();
int selectiec = toernooienUitvoer.getSelectedColumn();
String primarykey = (String) toernooienUitvoer.getValueAt(selectie, 0).toString();
String waarde = toernooienUitvoer.getValueAt(selectie, selectiec).toString();
String columnaam = toernooienUitvoer.getModel().getColumnName(selectiec).toString();
String input = JOptionPane.showInputDialog("wijzig geselecteerde data", waarde);
toernooienUitvoer.setValueAt(input, selectie, selectiec);
PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET ? = ? WHERE toernooi.T_code = ?");
stat.setString(1, columnaam);
stat.setString(2, input);
stat.setString(3, primarykey);
Guys, i know the query is correct, if i input the values. my guess my mistake is somewhere in the preparedstatement
i am getting a MySQLSyntaxErrorException:
As mentioned in other answer, the placeholder ? can only be used for values, not for table and column names. Since you are not reusing the PreparedStatement this is quite simple.
Change from
PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET ? = ? WHERE toernooi.T_code = ?")
to
PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET " + columnName + " = ? WHERE toernooi.T_code = ?")
And adjust the index parameter in the setString calls.
I don't think you can use place holder for dynamically passing the column name,your query should be:
"UPDATE fullhouse.toernooi SET colname = ? WHERE toernooi.T_code = ?"
When you use bind variables, it means the statement is precompiled and on the next executions, it will be faster. You are trying to make the name of the column to be a bind variable, which is not possible.
because you obviously need to update several different columns, in order to achieve some speed, you should declare several prepared statements, one for each column. Keep them in a HashMap<String, PreparedStatement>
The column name of a prepared statement cannot be dynamic because, depending on the column name, the query plan will be wildly different (e.g. sometimes table scan will be the fastest, sometimes using an index, sometimes something even more esoteric).
If SQL can't rely on a certain plan being the fastest, it needs to come up with a new one every time - which means there's no point in making a prepared statement which is why you can't do it.
I wish to generate reports for my application, one such report requires to display list of orders given today. For that I have the following method in my ejb which returns nothing (debugged and found so):
public Collection<OrderStock> getOrderReport(String userName) {
String strQuery = null;
strQuery = "Select o from OrderStock o where o.userName.userName = :userName and o.orderDateTime = :orderDateTime";
Collection<OrderStock> c = em.createQuery(strQuery).setParameter("userName",userName).setParameter("orderDateTime", new Date(),TemporalType.DATE).getResultList();
return c;
}
How do i solve it? Why does it return nothing?
edited:
I am using mysql as backend
datatype of orderDateTime is DateTime
eg os data in orderDateTime : 2012-06-05 00:12:32
2012-06-05 11:34:42
2012-04-05 12:32:45
You have a DateTime column, and are looking for posts on a single date. I suspect this datetime column contains seconds or miliseconds since the Epoch. You can't compare times to dates, so you will have to convert the day to a time. Actually two times that describe the day.
SELECT o
FROM OrderStock o
WHERE
o.userName.userName = :userName
AND (
o.orderDateTime >= FirstSecondOfTheDay
OR o.orderDateTime <= LastSecondOfTheDay
)
Depending on your database system you can calculate these seconds (or milliseconds, i don't know your table) using the database or rather do it in java
You can not use Date() as simple as that. The date persisted in the DB will definitely have different format. So the best thing to do is to look into the method used to persist the data in the first place and use the same method to fetch back the data.
The method might by Oracle function, java method. You need to investigate further into this.
Try this for MySQL:
strQuery = "Select o from OrderStock o where o.user.userName = :userName and date(o.orderDateTime) = :orderDateTime";
Date today = DateUtils.truncate(new Date(), Calendar.DATE);
Collection<OrderStock> c = em.createQuery(strQuery).setParameter("userName",userName).setParameter("orderDateTime", today ,TemporalType.DATE).getResultList();