Java JDBC First () in ResultSet is not working? - java

I want to change the position of the cursor to the first row but I don't know why my code is not working.when I add rs2.first():
and also I am getting this error :
This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).
try{
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
String url = "jdbc:derby://localhost:1527/test";
Connection conn = DriverManager.getConnection(url);
String query = "select * from APP.RANKING";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query);
while (rs.next()){
String BID = rs.getString("BALLOT_ID");
String CN = rs.getString("CANDIDATE_NAME");
String ROID = rs.getString("USER_ID");
Ro1_ID = ROID;
String RA = rs.getString("RANK");
int rowNum = rs.getRow();
int rowNum2;
boolean In_check = false;
while(rs2.next()){
In_ballot.addElement(BID);
}
rs2.First();
In_ballot.addElement(BID);
}
}
catch(Throwable e) {
System.err.println(e.getMessage());
}
this.InB_list.setModel(In_ballot);

By default, calling createStament() in a connection results in every ResultSet having type 'TYPE_FORWARD_ONLY' - This results in the exception you see using first().
Instead, use another versions of createStatement, like this one.
This sample of creating scrollable ResultSets in Derby might help.

Related

Unable to connect to LAN server; no exception is shown

I have tried to use another proyect and the connection is succesfull but from this proyect I am only able to connect to localhost mysql. I want it to work only on lan.
I am getting "Access denied for user 'root'#'192.168.1.70' (using password: YES)"
Code sample from not working proyect:
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
st = (Statement) con.createStatement();
String s = "SELECT * FROM meta";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
while(rs.next()){
int meta = rs.getInt("meta");
goal.setText(Integer.toString(meta));
}
}catch(Exception e){}
finally{
try{ st.close();
rs.close();
con.close();
}
catch(Exception e){ JOptionPane.showMessageDialog(null, "InformaciĆ³n no encontrada");
}
}
Code sample from another proyect which connects succesfully
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://192.168.1.66:3306/jjeventoscore";
Class.forName(myDriver);
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM client";
// create the java statement
Statement st = (Statement) conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()){
String name = rs.getString("name");
String last = rs.getString("last");
String h_phone = rs.getString("h_phone");
String m_phone = rs.getString("m_phone");
String of_phone = rs.getString("of_phone");
String ex_phone = rs.getString("ex_phone");
String email = rs.getString("email");
String medium = rs.getString("medium");
System.out.println(name+" "+last);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
You need to give privileges to the user on that Database and that Table.
With privileges, on your MySQL instance:
USE jjeventoscore;
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70';
Or maybe try
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70' IDENTIFIED BY '';
Since it says "Using password: YES"
Also, check the password on MySQL. It should match the parameter in this function
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");

how i can search in database using jTextField

hi every one i have write program that connect to database i create jTextField and jTable my question is how i can use the jTextField to serch in database and view in jTable the code i try is below
try{
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
Connection con = DriverManager.getConnection( host, uName, uPass);
String sql = "Select * from ITEMB where ITEM '"+asdf.getText()+"'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String pr = rs.getString("PRISE");
String it= rs.getString("ITEMNAME");
String itm = rs.getString("ITEM");
String[] data = {pr, it, itm};
tabMode.addRow(data);
double price = Double.parseDouble(rs.getString("prise"));
totalpay = price + totalpay;
++rowCount;
}
}
catch (Exception e) {
//ignore
}
jTextField3.setText(String.valueOf(totalpay));
}
Don't ignore the Exception. How to you expect to debug your SQL if you don't display error messages???
I would guess the problem is you are missing an "=" from your select statement (ie. "ITEM = asdf.getText()").
However, the better way to use SQL is to use a PreparedStatement so you don't have to worry about all the delimiters. So the SQL might be something like:
String sql = "Select * from ITEMB WHERE ITEM = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, asdf.getText() );
stmt.executeQuery();
stmt.close();
It is much easier to read an maintain.

How to compare Two Resultset Columns values in Java?

Can anyone tell me how I can compare two resultset values? Only getting error in if statement, but the rest is working.
Statement s = con.createStatement();
Statement stmnt = con.createStatement();
String query = "select * from tbl_product";
s.execute(query);
ResultSet rs = s.getResultSet();
while(rs.next())
{
String strOuter=rs.getString(2);
System.out.println(strOuter);
String query1 = "select * from PRODUCTS_AJ";
stmnt.execute(query1);
ResultSet rs1 = stmnt.getResultSet();
while(rs1.next())
{
System.out.println("-------"+rs1.getString(2));
if(rs.getString(2).equals(rs1.getString(2)))// Getting Error here for this line
{
System.out.println("Found");
}
}
}
java.sql.Exception data not found
This types of error occurs when you try to read same column of the same cursor multiple times. And what you encountered is a typical scenario. Just store the string temporarily like bellow:
String col3 = rs1.getString(2);
and use col3 instead of rs1.getString(2), whenever needed.
System.out.println("-------"+ col3);
if(col3.equals(rs1.getString(2)))
{
...
You cannot re-read a column value again. So, copy it in a local variable for logging.
String val = rs1.getString(2);
System.out.println("-------" + val);
if (rs.getString(2).equals(val)) {
What you could possibly do is
use SQL where clause
String query1 = "select * from PRODUCTS_AJ where fieldNmae = 'something'";
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
if (colCount > 1)
{
// found
}
For ResultSetMetaData
or possibly do
ResultSet rsOLD = null;
ResultSet rs = s.getResultSet();
// rs will be new ResultSet
while(condition)
{
// check from second row (maintain if case)
.
.
.
// end of loop
rsOLD = rs;
}
Ok ! This is a typical error while using JDBC-ODBC bridge driver with MS Access. I have experienced.I solved it in following way. Retrieving the same data more than once from the result set.
Please try like this
ResultSet rs = s.getResultSet();
String str=rs.getString(2);
Use this string to compare
str.equals(rs2.getString(2)
Thanks!
rs.getSting(2) is executed the number of row times of rs1 in the while loop of rs1. You may not have the that many number of rows in rs as rs1.

A lock could not obtained within the time requested issue

The title is the error I'm getting, when I click load my program freezes. I assume it's because I'm doing a statement inside a statement, but from what I see it's the only solution to my issue. By loading, I want to just repopulate the list of patients, but to do so I need to do their conditions also. The code works, the bottom method is what I'm trying to fix. I think the issue is that I have 2 statements open but I am not sure.
load:
public void DatabaseLoad()
{
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
PatientList.clear();
Statement stmt8 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL8 = "SELECT * FROM PATIENTS";
ResultSet rs8 = stmt8.executeQuery( SQL8 );
ArrayList<PatientCondition> PatientConditions1 = new ArrayList();
while(rs8.next())
{
PatientConditions1 = LoadPatientConditions();
}
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTS";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
int id = (rs.getInt("ID"));
String name = (rs.getString("NAME"));
int age = (rs.getInt("AGE"));
String address = (rs.getString("ADDRESS"));
String sex = (rs.getString("SEX"));
String phone = (rs.getString("PHONE"));
Patient p = new Patient(id, name, age, address, sex, phone,
PatientConditions1);
PatientList.add(p);
}
UpdateTable();
UpdateAllViews();
DefaultListModel PatientListModel = new DefaultListModel();
for (Patient s : PatientList) {
PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());
}
PatientJList.setModel(PatientListModel);
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
}
This is the method that returns the ArrayList of patient conditions
public ArrayList LoadPatientConditions()
{
ArrayList<PatientCondition> PatientConditionsTemp = new ArrayList();
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTCONDITIONS";
ResultSet rs5 = stmt.executeQuery( SQL );
int e = 0;
while(rs5.next())
{
e++;
String ConName = (rs5.getString("CONDITION"));
PatientCondition k = new PatientCondition(e,ConName);
PatientConditionsTemp.add(k);
}
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
return PatientConditionsTemp;
}
I had a similar problem.
I was connecting to derby db hosted on local server.
I created 2 simultaneous connections:
With squirrel
With ij tool
When a connection makes a modification on a table, it first gets a lock for the particular table.
This lock is released by the connection only after committing the transaction.
Thus if the second connection tries to read/write the same table, a msg prompts saying:
ERROR 40XL1: A lock could not be obtained within the time requested
To fix this, the connection which modified the table has to commit its transaction.
Hope this helps !
Here is a good place to start: http://wiki.apache.org/db-derby/LockDebugging
You need to close your statement and result set as well so that when you restart your program they won't be open. Add stmt.close(); and rs.close(); at the end of your lines of code within the try and catch statement.
Why could you not use the same connection object to do both the queries?
Like pass that connection object to the LoadPatientConditions() as a parameter and use it there.

Cannot process the resultset in jsp

I was trying to call a method in jsp which returns a resultSet. Like,
In JSP:
OracleResultSet rs = null;
rs = getMyValuesHere();
out.println("rs:"+rs);
// rs is not null.Something like oracle.jdbc.driver.OracleResultSetImpl#1f1e1f
How can I retrieve my values here from the resultSet?
because not even entering into this while loop. ,
while(rs.next()) {
}
Method is:
<%!
public OracleResultSet getMyValuesHere()
{
OracleConnection connection = null;
OraclePreparedStatement ptmst = null;
OracleResultSet rs = null;
OracleCallableStatement cstmt = null;
StringBuffer sql = new StringBuffer();
//My query goes here
connection = (OracleConnection) TransactionScope.getConnection();
sql.append("SELECT DISTINCT something.... ");
rs = (OracleResultSet)ptmst.executeQuery();
return rs;
}
%>
I tried printing the data in getMyValuesHere()
rs = (OracleResultSet)ptmst.executeQuery();
while (rs.next())
{
// rs.getString(1)) -- I was able to print this.
}
You didn't specified the Database Driver in your program.. Include the driver in your program and then try it once

Categories