i have try to develop one java app.here am getting information from mysql database.
my code is:
public class RetailerWs {
public int data(){
int count=0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro","root","");
PreparedStatement statement = con.prepareStatement("select * from orders where status='Q' AND MONTH(date) = MONTH(CURDATE()) AND YEAR(date) = YEAR(CURDATE())");
ResultSet result = statement.executeQuery();
while(result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return count;
}
}
the other class is :
public class Demo {
public static void main(String[] args){
RetailerWs obj = new RetailerWs();
System.out.println(obj.data());
}
}
Here i have to check the query and display count value is successfully.but my doubt is the query matched item is zero means the output is displayed blankly.but i wish to need it is display 0.not display blank screen..so please help me how is to do.
Create the object of class RetailerWs.
RetailerWs obj =new RetailerWs ();
System.out.println(obj.data());
The statement
System.out.println(new RetailerWs().data());
wil always, unconditionally print an integer value, even if that value is 0. Unless an exception prevents it from executing, that is.
Related
I want to make a small "event apply page" for training.
(the event is First-come, first-served basis.)
I'm using JSP, JAVA(DAO(Data Access Object)) and oracle JDBC.
When a customer clicks "apply" button,
[1. id], [2. apply date], [3. apply count (+1)] will be saved in db table that I made.
I don't know how to make login session yet.
So I made input field that can input id directly when applying.
I can insert and get from db table about id and apply date.
But I'm trouble because "apply" counting.
I will put limit that no more apply when "apply count" is 100. (First-come, first-served basis)
How to insert apply count to DB and how to get count number from DB?
here is my code and situation.
1. DB TABLE
Column that I made are 3
[1. id] / [2. aug_cnt] / [3. applydate]
enter image description here
2. Applybean.java
package model;
import java.sql.Timestamp;
public class ApplyBean {
private String id ;
private int aug_cnt;
private Timestamp applydate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAug_cnt() {
return aug_cnt;
}
public void setAug_cnt(int aug_cnt) {
this.aug_cnt = aug_cnt;
}
public Timestamp getApplydate() {
return applydate;
}
public void setApplydate(Timestamp applydate) {
this.applydate = applydate;
}
}
3. ApplyDAO.java
public class ApplyDAO {
Connection con;
PreparedStatement pstmt;
ResultSet rs;
public void getCon() {
try {
Context initctx = new InitialContext();
Context envctx = (Context)initctx.lookup("java:comp/env");
DataSource ds = (DataSource)envctx.lookup("jdbc/pool");
con = ds.getConnection();
}catch(Exception e) {
e.printStackTrace();
}
}
public void insertApply(ApplyBean abean) {
try{
getCon();
String sql = "insert into eventcount_aug values(?,sysdate)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, abean.getId());
pstmt.setTimestamp(2, abean.getApplydate());
pstmt.executeUpdate();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I think I need to edit only "Applybean.java" file...
If I realize how to insert and get "apply count",
I can find how to make my event page perfectly.
I would be really grateful for your help.
Thank you.
If I am understanding your question correctly, you need following things:
Create sequence object in oracle:
create sequence my_test_id_seq increment by 1;
Alter your Oracle table & use this sequence as default value:
alter table eventcount_aug modify (aug_cnt number default my_test_id_seq.nextval);
By this, you got capability that your aug_cnt column gets automatically incremented whenever there are inserts.
You can then use select max(aug_cnt) as count from eventcount_aug; before your insert call in insertApply which will decide if you need to go ahead with insert or not. For this you can create one utility method something like:
private int getCount(){
try{
getCon();
int length=0;
String sql = "select max(?) as count from eventcount_aug";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,"aug_cnt");
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
length = rs.getInt(1);
}
con.close();
}catch(Exception e){
}
return length;
}
And then use this in your insertApply before try block:
public void insertApply(ApplyBean abean) {
if(getCount()<100){ // if count is less than 100, then only insert.
try{
..
}
Update : For oracle <12c versions , you can update your insert in your original insertApply method.:
String sql = "insert into eventcount_aug values(?,sysdate,my_test_id_seq.nextval)";
No need to re-create table or alter table & use sequence.
It seems that you don't care about revocation of the application or concurrency problem. You can use another SQL to get the current count number before you insert a new application.
select max(aug_cnt) as count from eventcount_aug;
And then if count < 100 then set new count as count + 1, or else if count >= 100 then refuse the new application.
I am getting error in if(rs.next()) and .getString on my code. This is my code
public void keyPressed(KeyEvent e) {
Function f = new Function();
Result rs = null;
String ans = "Key";
rs = f.find(jTextField1.getText());
try{
if(rs.next()){
jTextArea1.setText(rs.getString("Key"));
}
}catch(Exception ex){
}
}
OK the methods next() and getString() are parts of the java.sql.ResultSet interface. Your code should look like this:
public void keyPressed(KeyEvent e) {
Function f = new Function();
ResultSet rs = null;
String ans = "Key";
rs = f.find(jTextField1.getText());
try{
if(rs.next()){
jTextArea1.setText(rs.getString("Key"));
}
}catch(Exception ex){}
}
And if the Function objects method find(String search) returns a valid java.sql.ResultSet implementation, you can use next() to move pointer to next Result and to check if it has one. And then you can easyly use getString(String columnName) to get the value of a column as String.
I would return ResultSet in an method like this. Let your Function class method find directly return your desired value or null or empty string. Handling the ResultSet here isn't good practice. Keep your concerns together.
I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();
I retrieve the data from database and loop it thru an array to display the like amount.
public void SetUpLikeAmount() {
int likes = 0;
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likeArray.add(Integer.parseInt(resultSet.getString("likeDislike_likes")));
likes += likeArray.get(count);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
jLabel_like.setText(Integer.toString(likes));
}
However, it keeps returning 0. Thanks in advance.
(As an aside, it never returns anything - you've posted a void method.)
Look at this code:
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
...
}
You've just created a new ArrayList<Integer>, which will therefore have a size of 0. Therefore, the loop always completes immediately, without ever executing the body.
If you're trying to get input from a list created elsewhere, you should probably pass that into your method. (You should also use a PreparedStatement with a parameter instead of including the value directly in your SQL.)
You're iterating over the list likeArray which is empty. So it won't enter the loop
May be here is the new code you should refer:
public void SetUpLikeAmount() {
int likes = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += Integer.parseInt(resultSet.getString("likeDislike_likes"));
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
}
You might not need the arraylist I believe as you are getting the value and summing it during the iteration over the result set only.
I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}