I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.
Related
I am trying to understand why I can not search more than one record in a database with Java. It is a Java jsp application but I seems to struggle to figure out where the issue is. I am a beginner with jsp but I am sure would not make any difference
try{
String myDriver = "org.gjt.mm.mysql.Driver";//db driver
String myUrl = database;//connect to db
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, user, password);//authenticating on database
String query = "SELECT Cus_ID, Cus_name, Cus_surname, Cus_mail, Cus_Address, Cus_telephone FROM customerdb";//mysql select statement
PreparedStatement sta = conn.prepareStatement(query); //prepared statement
ResultSet rst = sta.executeQuery(query);
while (rst.next())
{
String cusid = rst.getString("Cus_ID"); //variable to retrieve the customer from the database
String cusn = rst.getString("Cus_name");
String cussn = rst.getString("Cus_surname");
String cusm = rst.getString("Cus_mail");
String cusaddr = rst.getString("Cus_Address");
String custel = rst.getString("Cus_telephone");
if(!(customer.equals(cusid))){
request.setAttribute("al", "user not found");
request.getRequestDispatcher("account.jsp").forward(request, response); //and user will stay on login page
}if(customer.equals(cusid)){
System.out.println("hello" + cusid);
request.setAttribute("ID", cusid);
request.setAttribute("name", cusn);
request.setAttribute("surname", cussn);
request.setAttribute("mail", cusm);
request.setAttribute("address", cusaddr);
request.setAttribute("telephone", custel);
request.getRequestDispatcher("account.jsp").forward(request, response);
}else{
}
}
}catch(ClassNotFoundException | SQLException | HeadlessException ex) {
Logger.getLogger(LogInController.class.getName()).log(Level.SEVERE, null, ex);
}
The PreparedStatement#executeQuery() method does not take any parameters. Change this:
ResultSet rst = sta.executeQuery(query);
to this:
ResultSet rst = sta.executeQuery();
This is a somewhat common mistake when using this API. You may have other issues with your code as well, but this should make a noticeable improvement.
I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.
public Abstract() throws Exception {
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
initComponents();
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT ID from bidding_abstractofprices";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
while(rs.next()){
int id = Integer.parseInt(rs.getString("ID")) + 1;
lblTransacID.setText(String.valueOf(id));
}
}catch (Exception ex){
}
}
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:
public Abstract() throws Exception {
// Allow all your components to initialize first.
initComponents();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
int id = 0;
while(rs.next()){
id = rs.getInt("ID") + 1;
}
lblTransacID.setText(String.valueOf(id));
rs.close();
st.close();
cn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
My Title might not be clear enough. So let me explain the problem . I have to retrieve the values from the database store it in an array list and display it in a jsp page dynamically. for that am using a query
select customer,
id,
0 message
from TableName
My Table Structure:
customer varchar2(20)
id Number
I don't know how to add the column 0 message into the result set since this column is not present in that table.
For example, if we give
select 0 message
from TableName;
The output of the above query will be
message
0
So now my question is how to add this column(message) into my Resultset and Array list?
When you add it to your SQL-query as in your question it should also appear in the resultset...
Just wondering if you are facing any issue with executing the SQL query with the additional (non-existing in DB) column through JDBC.
for eg: - you can execute the below query directly in the database through JDBC
select customer,
id,
0 "message"
from TableName
Sample Code snippet.
Connection conn = DriverManager.getConnection(".....", "...","..");
ps = conn.prepareStatement("select customer, id, 0 \"message\" from your_table");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.printf("%s %s %s", rs.getString("id"), rs.getString("customer"), rs.getString("message"));
}
Hlo.. below code will help you..
package com.smk.jdbc.ps;
import java.util.ArrayList;
public class PreparedStatement {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.OracleDriver");
java.sql.Connection conn = null;
java.sql.PreparedStatement ps = null;
String strQry = "select 1 message from dual where 1 = ?";
conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:#localhost:wzdev", "user","pwd");
ps = conn.prepareStatement(strQry);
ps.setInt(1, 1);
java.sql.ResultSet rs = ps.executeQuery();
while(rs.next()){
java.util.ArrayList<java.sql.ResultSet> ars = new ArrayList<java.sql.ResultSet>();
ars.add(rs);
System.out.println(ars.get(0).getInt("message"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
This code is working fine for sql server.And doing same for whatever u want.
public class ConnectionPool
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("","","");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select sRowId, 0 messa from tblAccount");
while(rs.next())
{
list.add(rs.getInt("messa"));
}
System.out.println(list.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.
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.