2 problems, it outputs 1 2 3 4 3 5, instead of 1 2 3 4 5, which I'm not sure why followed by success but does not print out the data from the SQL table
Statement st = null;
ResultSet rs = null;
try {
System.out.println("1");
Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("2");
//Class.forName(driver);
System.out.println("3");
st = con.createStatement();
rs = st.executeQuery("SELECT productcost " +
"FROM producttable " +
"WHERE productid = 3;");
System.out.println("4");
if (rs.next()) { //get first result
System.out.println(rs.getInt(1)); //coloumn 1
}
System.out.println("5");
System.out.println("Success");
} catch (Exception e) {
System.out.println("Error");
}
The reason you are seeing 3 in-between 4 and 5 is because the ResultSet contains 3.
ResultSet.getInt
Retrieves the value of the designated column in the current row of
this ResultSet object as an int
Try debugging your code and stepping through that section. You'll see what I am displaying below.
You must have '3' as a data in first column! Cause your printing the data of first column of record.i don't see any problem here!
Related
I'm trying to make login code in java but there's some problem in my code.
If I enter correct data or wrong one still can't enter the loop to
go to next frame.
This is full code it's already have exception so it's not the problem .
Connection conn = null ;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB?"+
"user=name&password=pass&characterEncoding=utf8");
String query = ("Select User_Name from user where User_Name = '" + txtUserName + "'
and password = '" + passwordField.getPassword().toString() + "' ; ");
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.wasNull()) {
System.out.println("true");
frame2.setVisible(true);
frame.setVisible(false);
break;
}
}
catch (SQLException ee)
{
JOptionPane.showMessageDialog(frame2, "Wrong inf ... please try again ");
}
I try this too but still not working.
Connection conn = null ;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB?"+
"user=name&password=pass&characterEncoding=utf8");
PreparedStatement stmt = null;
String query = "Select User_Name from user where User_Name =? and password=?";
stmt = conn.prepareStatement(query);
stmt.setString(1, txtUserName.getText());
stmt.setString(2, passwordField.getPassword().toString());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("true");
frame2.setVisible(true);
frame.setVisible(false);
break;
}
}
catch (SQLException ee)
{
JOptionPane.showMessageDialog(frame2, "Wrong inf ... please try again ");
}
I'm not really a Java programmer but a quick glance at your code and the descriptions of ResultSet::wasNull() ResultSet::next() show me you're misusing or misunderstanding how those work.
wasNull() tells you if the current column contains a null. An empty set is not null!
next() moves the cursor forward one row and returns true if the new current row is valid. False otherwise. In other words, if you have zero or one valid row, next() will immediately return false.
So, let's put things together.
Case 1: Using wasNull():
Enter valid data. ResultSet contains a non-null result. wasNull() returns false, don't enter while loop.
Enter invalid data. ResultSet contains an empty set result. wasNull() returns false, don't enter while loop.
Case 2: Using next():
Enter valid data. ResultSet contains a single non-null result. next() moves to next row [which is invalid] and returns false, don't enter while loop.
Enter invalid data. ResultSet contains a single empty set result. next() moves to next row [which is invalid] and returns false, don't enter while loop.
Might I suggest spending some time reading the ResultSet API documentation: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
I am having an issue where i connect to the database,but cannot retrieve more than the first column even though my query statement is "Select * from Users"
below is my code:
import java.sql.*;
public class Connecttodb {
public void dbConnect(String db_connect_string,String db_UserID,String db_UserPass)
{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,db_UserID,db_UserPass);
System.out.println("connected");
Statement statement= conn.createStatement();
String querystring = "SELECT * FROM Users";
ResultSet rs = statement.executeQuery(querystring);
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connecttodb connServer= new Connecttodb();
connServer.dbConnect("jdbc:sqlserver://TGOURDINE-PC\\SQLEXPRESS;databaseName=picture website", "tgourdine", "thomas");
}
}
the result is only the first column, UserID:
connected
1
2
3
The result i want is as follows:
connected
1 tgourdini thomas NULL NULL
2 Geoff Marley NULL NULL
3 tara Elaine NULL NULL
thank you,
According to the documentation getString(1) will return only the first column.
Because you only retrieve the first column
System.out.println(rs.getString(1));
Change your loop to
while(rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
Have a look at the documentation of getString
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Also have a look at the received parameter documentation
columnIndex - the first column is 1, the second is 2, ...
This question already has answers here:
java.sql.SQLException: Illegal operation on empty result set. when authenticating
(2 answers)
Closed 2 years ago.
I'm trying to build a pay desk in a grocery store and my code actually performs what I intend for it to do, but for one thing.
After I ask the user to enter how many of an item they want, the product information is gathered and works fine, but when it's supposed to ask the user to enter product-ID for next product, the line is repeated and I get the following exception in my catch: "Illegal operation on empty result set". Again, all the calculations and everything is fine except for the repeating of that line. Any ideas on what might be the problem?
The output that is repeat is like this:
Enter product (or Exit):
ERROR1: Illegal operation on empty result set.
Enter product (or Exit):
And here's the code.
try {
Class.forName("com.mysql.jdbc.Driver");
String connection = "jdbc:mysql://myDB?";
connection = connection + "user=xxx&password=xxxxxx";
Connection conn = DriverManager.getConnection(connection);
// MATA IN PRODUKTNUMMER
System.out.println("\nEnter product (or Exit):");
GroceryStore.input = GroceryStore.scan.nextLine();
PreparedStatement stmt = conn.prepareStatement(
"SELECT * "+
"FROM Products "+
"WHERE productNo = ?");
stmt.setString(1, GroceryStore.input);
ResultSet rs = stmt.executeQuery();
rs.next();
pName = rs.getString("productName");
System.out.println("Product: " + pName);
// MATA IN ANTAL
System.out.println("\nEnter amount:");
GroceryStore.amount = GroceryStore.scan.nextInt();
pPrice = rs.getDouble("productPrice");
priceRounded = new BigDecimal(pPrice).setScale(2, BigDecimal.ROUND_FLOOR);
amountRounded = new BigDecimal(GroceryStore.amount).setScale(0);
priceRounded = priceRounded.multiply(amountRounded);
GroceryStore.sum = GroceryStore.sum.add(priceRounded);
inOut.output();
inOut.input();
conn.close();
}
catch (Exception e) {
System.out.println("ERROR1: " + e.getMessage());
}
You are not checking whether your result set has any data or row in it.
ResultSet rs = stmt.executeQuery();
rs.next();
...
...
You should check whether your result is empty or having any row:
ResultSet rs = stmt.executeQuery();
if(rs.next()){
.....
your code
.....
}
You haven't checked Whether your result set is empty or not before actually retriving values from Result set...
next() returns true if there is a data in the result set, false it there is not data at the a cursor position
Place your code like this
While(rs.next())
{
pName = rs.getString("productName");
System.out.println("Product: " + pName);
// MATA IN ANTAL
System.out.println("\nEnter amount:");
GroceryStore.amount = GroceryStore.scan.nextInt();
pPrice = rs.getDouble("productPrice");
}
i have used a select command in my java program and stored its value in the result set. now while looping in the resultset i want to use a select command which will select the first 5 lines of the resultset and insert into other table. for the second time, it should select the next 5 lines and insert into the table. and for the third time, so on..
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
}
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
while(res.next() && (res.getRow()%5) !=0){
//select from this table
//call insert method(what selected)
}
}
I would suggest changing your query using LIMIT and using a PreparedStatement. Something like:
SELECT * FROM table1 LIMIT ?,?
This has a couple of advantages:
You are not fetching everything in one shot - can be sometimes a performance benefit if you've a lot many rows to deal with in your table
You can change pre-define the number of elements that you want to fetch in every single batch
So your code will look something like this:
PreparedStatement ps = null;
ResultSet rs = null;
final int FETCH_LIMIT = 5; //number of elements to fetch per batch
final int BATCH_LIMIT = 3; //number of batches you would want
int currentRows = 0;
try{
ps = connection.prepareStatement("SELECT * FROM table1 LIMIT ?,?");
for(int currentBatch = 0; currentBatch < BATCH_LIMIT; currentBatch++){
ps.clearParameters();
ps.setInt(1, currentRows);
ps.setInt(2, currentRows + FETCH_LIMIT);
try{
rs = ps.executeQuery();
while(rs.next()){
// do your work
}
}catch(Exception exe){
//manage exception
}finally{
//manage resultset
}
currentRows += FETCH_LIMIT;
}
}catch(Exception exe){
//Handle your exception
}
finally{
//Manage your resources
}
Please add a falg and use that is it
int i=0;
while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}
Create another insert query dynamically inside the while loop and execute it outside the while loop
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmmSS");
String strCurrDate = formatter.format(new java.util.Date());
String strfileNm = "Customer_" + strCurrDate + ".txt";
String strFileGenLoc = strFileLocation + "/" + strfileNm;
String Query1="select '0'||to_char(sysdate,'YYYYMMDD')||'123456789' class_code from dual";
String Query2="select '0'||to_char(sysdate,'YYYYMMDD')||'123456789' class_code from dual";
String Query3="select param from dual";
try {
Statement stmt = null;
ResultSet rs = null;
Statement stmt1 = null;
ResultSet rs1 = null;
stmt = conn.createStatement();
stmt1 = conn.createStatement();
stmt2 = conn.createStatement();
rs = stmt.executeQuery(Query1);
rs1 = stmt1.executeQuery(Query2);
rs2 = stmt2.executeQuery(Query3);
File f = new File(strFileGenLoc);
OutputStream os = (OutputStream)new FileOutputStream(f,true);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw);
while (rs.next() ) {
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write(" ");
}
bw.flush();
bw.close();
} catch (Exception e) {
System.out.println(
"Exception occured while getting resultset by the query");
e.printStackTrace();
} finally {
try {
if (conn != null) {
System.out.println("Closing the connection" + conn);
conn.close();
}
} catch (SQLException e) {
System.out.println(
"Exception occured while closing the connection");
e.printStackTrace();
}
}
return objArrayListValue;
}
The above code is working fine. it writes the content of "rs" resultset data in text file
Now what i want is ,i need to append the
the content in "rs2" resultset to the "same text file"(ie . i need to append "rs2" content with "rs" content in the same text file)..
------------------edit part----------------
stmt = conn.createStatement();
stmt1 = conn.createStatement();
stmt2 = conn.createStatement();
rs = stmt.executeQuery(Query1);
rs1 = stmt1.executeQuery(Query2);
rs2 = stmt2.executeQuery(Query3);
while ( rs.next() ) {
while(rs1.next()){
while(rs2.next()){
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\t");
bw.write(rs1.getString(1)==null? "":rs1.getString(1));
bw.write("\t");
bw.write(rs2.getString(1)==null? "":rs2.getString(1));
bw.write("\t");
bw.newLine();
}
}
}
Above code working fine.
My problem is
"rs" resultset contains one record in the table
"rs1" resultset contains 5 record in the table
"rs2" resultset contains 5 record in the table
"rs" data is getting recursive.
while writing to the same text file , the output i am getting like
1 2 3
1 12 21
1 23 25
1 10 5
1 8 54
but i need output like below
1 2 3
12 21
23 25
10 5
8 54
What things i need to change in my code.. Please advice
-----------------edit part1------------------
Expected Result is
1 2 3
1 12 21
1 23 25
1 10 5
1 8 54
but output i got like
1 2 3
12 21
23 25
10 5
8 54
new FileOutputStream(f,true);
You have already set the append flag to true(the second argument), so do the same as what you did with the previous result set.
See: http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html