What is the best way to get the max id of table? Below I have paste the error and code. So I was planning on using afterLast() method to get the max id but I get an error.
ERROR:
SQLException: feature not supported
Code:
public class ex03 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave_000/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/T_01_JDBC_01.accdb";
Connection con;
// Get Max ID
Statement stmt0;
String query0 = "select * from user";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "", "");
stmt0 = con.createStatement();
// Get last ID
ResultSet rs = stmt0.executeQuery(query0);
rs.afterLast();
int maxID = rs.getInt("ID");
System.out.println(maxID);
pstmt1.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
It is much more efficient to use SQL to find the maximum value:
select max(id) from user
Related
I have the following method that I use with Spring JDBC
public String getState() {
String stateLink = template.queryForObject(
"select state_url from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1",
(result, rowNum) -> {
return result.getString("state_url");
});
return stateLink;
}
I can't find an example of how to do a for update with Spring JDBC. I want in_use to be set to true using for update.
I need to use select for update since this application will be used in a multi-threaded fashion. I don't want more than one thread to get the same row and the way to prevent that is by using select for update
I was able to do this with plain JDBC, here is the question I asked how to do it with plain JDBC
select "for update" with JDBC?
Anyone know how this would be done?
This is what I came up with, feel free to recommend improvements
public String getState() throws SQLException {
String state = null;
Connection conn = DataSourceUtils.getConnection(template.getDataSource());
try {
conn.setAutoCommit(false);
String[] colNames = { "id", "state_url", "in_use" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1 FOR UPDATE";
System.out.println(query);
try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
// Get the current values, if you need them.
state = rs.getString(colNames[1]);
rs.updateBoolean(colNames[2], true);
rs.updateRow();
conn.commit();
}
}
} catch (SQLException e) {
conn.setAutoCommit(true);
e.printStackTrace();
} finally {
conn.setAutoCommit(true);
}
return state;
}
I'm trying to get values from resulset, but it return nothing.
When i'm trying to do it through plain sql it return some values.
List<String> res = new ArrayList<String>();
try {
String query = "SELECT COLUMN_NAME FROM idoc.columns_to_show where user = ? "
+ DAO.DB2_UR_POSTFIX;
Connection connection = Properties.getDocsConnection();
try {
PreparedStatement pr = connection.prepareStatement(query);
try {
pr.setString(1, user.getDomainName());
ResultSet rs = pr.executeQuery();
try {
while (rs.next()) {
res.add(rs.getString("COLUMN_NAME"));
}
} finally {
rs.close();
}
} finally {
pr.close();
}
} finally {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return res;
Don't use column name "user" it is reserved name for DB2 database.
Therefore I couldn't find any result.
I'm having problem sorting my items from jcombobox, here are my codes.
public void fillCombo()
{
String dataSourceName = "CheckWriterDB";
String dbURL = "jdbc:odbc:" + dataSourceName;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(dbURL, "", "");
st = con.createStatement();
st.execute("select Suppliers from SuppliersTable");
rs = st.getResultSet();
if(rs!=null)
{
while(rs.next())
{
temp = rs.getString(1);
listOfSuppliersCombo.addItem(temp1);
}
}
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("Your error is: " + e);
}
}
Can anybody help me on how to sort the item shown in my JComboBox, data source of the items shown in my combobox is from my DATABASE. Thank you so much.
Use order by in your query to retrieve data ordered from your database
st.execute("select Suppliers from SuppliersTable order by <fields>");
Syntax: http://en.wikipedia.org/wiki/Order_by_(SQL)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == jButton1) {
String ab = jTextField1.getText();
String bc = jPasswordField1.getText().toString();
String cd = jTextField2.getText();
String de = jTextField3.getText();
PreparedStatement ps1 = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "hr");
ps = c.prepareStatement("Select User_Name from AdminLogin where Password =?");
ps.setString(1, bc);
rs = ps.executeQuery();
rs.next();
if (ab.equals(rs.getString(1))) {
ps1 = c.prepareStatement("Update AdminLogin SET Date1=?,Time=? WHERE Password=?");
ps1.setString(1, cd);
ps1.setString(2, de);
ps1.setString(3, bc);
int e = ps1.executeUpdate();
JOptionPane.showMessageDialog(this, "Welcome", "Logged In", JOptionPane.INFORMATION_MESSAGE);
//MainMenuAAI mainMenuAAI = new MainMenuAAI();
//setVisible(false);}
} else if (!(ab.equals(rs.getString(1)))) {
JOptionPane.showMessageDialog(this, "<html>YOU ARE NOT A<br>ADMIN</br></html>", "ERROR", JOptionPane.ERROR_MESSAGE);
//AdminLogin admin=new AdminLogin();
//setVisible(false);
}
c.close();
} catch (Exception e) {
System.out.println(e);
}
}// TODO add your handling code here:
}
Everything is working fine in the code. It is executing the code inside
if(ab.equals(rs.getString(1)))
and showing "Welcome" but not d one inside
if(!(ab.equals(rs.getString(1))))
Whenever I enter wrong username or password it shows the error
java.sql.SQLException: Exhausted Resultset
That is correct, because if you enter wrong username or password, NO record will be returned. So, when you use the rs.next(); in this case, it is trying to access the first row of the empty result set! And that is where it is throwing the exception.
You could fix your code like this:
rs = ps.executeQuery();
//rs.next();
int counter=0;
while (rs.next()) {
counter++;
if (ab.equals(rs.getString(1))) {
ps1 = c.prepareStatement("Update AdminLogin SET Date1=?,Time=? WHERE Password=?");
ps1.setString(1, cd);
ps1.setString(2, de);
ps1.setString(3, bc);
int e = ps1.executeUpdate();
JOptionPane.showMessageDialog(this, "Welcome", "Logged In", JOptionPane.INFORMATION_MESSAGE);
//MainMenuAAI mainMenuAAI = new MainMenuAAI();
//setVisible(false);}
}
}
if(counter==0){
JOptionPane.showMessageDialog(this, "<html>YOU ARE NOT A<br>ADMIN</br></html>", "ERROR", JOptionPane.ERROR_MESSAGE);
}
I'm trying to update a row in ResultSet, but it is throwing an error. I passed the constant value ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE to createStatement.
this is my code :
public void modifyPrice(float percentage) throws SQLException {
try {
con = util.connectdb();
con.setAutoCommit(false);
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from " + util.dbName
+ ".COFFEES");
while (rs.next()) {
float f = rs.getFloat("PRICE");
rs.updateFloat("PRICE", f * percentage);
rs.updateRow();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (st != null) {
st.close();
con.close();
}
}
}
When I executed this code block, the stack below got printed on console.
java.sql.SQLException: Invalid operation for read only resultset: updateFloat
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:197)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:261)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:269)
at oracle.jdbc.driver.BaseResultSet.updateFloat(BaseResultSet.java:236)
at oracle.jdbc.driver.OracleResultSet.updateFloat(OracleResultSet.java:677)
at tutorial.ModifyResultSet.modifyPrice(ModifyResultSet.java:29)
at tutorial.ModifyResultSet.main(ModifyResultSet.java:15)
Can anyone help me fix this error?
According to these links
http://www.coderanch.com/t/301466/JDBC/databases/Invalid-operation-read-only-resultset
http://www.coderanch.com/t/295932/JDBC/databases/updateXXX-function-ResultSet
instead of "select * from" you should use "select my_column_name from" statement.
See if it makes any difference.