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)
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.
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
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);
}
After batch insert a number of rows, I wish to retrieve the generated keys along with their corresponding inserted rows. how do I do this efficiently? Naively I can use statement.getGeneratedKeys() to query the database for each row based on each generated id, but that seems slow. the code below does a batch insert and then go through all the results in the table, however I don't want to include data that already exists in the table prior to insertion.
is there an alternative?
public static void main(String[] args) throws Exception {
Connection conn = getMySqlConnection();
ResultSet rs = null;
Statement stmt = null;
try {
conn = getMySqlConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
conn.setAutoCommit(false);
stmt.addBatch("INSERT INTO survey(id, name) VALUES('11', 'Alex')");
stmt.addBatch("INSERT INTO survey(id, name) VALUES('22', 'Mary')");
stmt.addBatch("INSERT INTO survey(id, name) VALUES('33', 'Bob')");
int[] updateCounts = stmt.executeBatch();
System.out.println(updateCounts);
conn.commit();
rs = stmt.executeQuery("SELECT * FROM survey");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
System.out.println("id="+id +" name="+name);
}
}
catch(BatchUpdateException b) {
System.err.println("SQLException: " + b.getMessage());
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor error code: " + b.getErrorCode());
System.err.print("Update counts: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
}
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor error code: " + ex.getErrorCode());
}
catch(Exception e) {
e.printStackTrace();
System.err.println("Exception: " + e.getMessage());
}
finally {
rs.close();
stmt.close();
conn.close();
}
}
You have a list of IDs you are interested in. You can use the 'id in (...,...,)' constraint:
StringBuilder newIds = new StringBuilder();
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
if (newIds.length() > 0) newIds.append(',');
newIds.append(rs.getInt(1));
}
if (newIds.length() > ) {
rs = stmt.executeQuery("SELECT * FROM survey where id in ("+newIds+")");
...
}