I have written the following code and the resultset (here its labelled as rs3) is returning true even though there is no result.I want to check if there is no result then the user has to enter correct phone manufacturer again.Don't know where I am going wrong?
BufferedReader r2 = new BufferedReader(new InputStreamReader(System.in));
String phone_manufacturer="";
boolean value1=true;
while (value1) {
System.out.println("\nPlease select your choice of phone manufacturer " );
String line = r2.readLine();
if (line.matches("[A-Za-z ]+$")) {
phone_manufacturer = line;
final String sql3 = "SELECT * from phone_model WHERE phone_type = '"+phone_type_choice+"' and manufacturer ='"+phone_manufacturer+"'";
st3 = connection.createStatement();
rs3= st3.executeQuery(sql3);
if(rs3!=null){
System.out.println("Model"+" "+"Manufacturer"+""+"Phone_type");
while(rs3.next()){
String modell = rs3.getString("Model");
String manufacturer = rs3.getString("Manufacturer");
String phone_type = rs3.getString("Phone_type");
System.out.format("%-25s%-20s%-10s\n",modell,manufacturer,phone_type);
}
}
else
{
System.out.println("The manufacturer isn't avaiable for the phone type choosen.Please try again");
value1=true;
continue;
}
value1=false;
}else
{
System.out.println("\nPlease enter correct manufacturer name " );
value1=true;
continue;
}
break;
}
Use :
if (!rs3.next() ) {
System.out.println("no data");
}
initially the ResultSet's cursor is pointing to before the first row, if the first call to next() returns false then there was no data in the ResultSet.
if you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst().
if (!rs3.isBeforeFirst() ) {
System.out.println("No data");
}
it's better to use prepared statment to avoid sql injection :
PreparedStatement updateemp = connnection.prepareStatement
("SELECT * from phone_model WHERE phone_type =? and manufacturer=?");
updateemp.setString(1,phone_type_choice);
updateemp.setString(2, phone_manufacturer);
How To use prepared statement.
Related
Im trying to get information in sql from database, there are two entries in each column but and with the following code, i am able to get the first entry information, if i wanted to get the second entry's records and display it also in project how would i get it?
String username1= rs.getString ("USERNAME");
String password1= rs.getString ("PASSWORD");
String aname1= rs.getString ("a_name");
String aname2= rs.getString ("a_name");
System.out.print("Enter Your Username: ");
String usernamea=(br.readLine());
System.out.print("Enter Your Password: ");
String passworda=(br.readLine());
if ((usernamea.equals(username1) && (passworda.equals(password1))))
{
System.out.println("Login Success! Welcome "+aname1+"!");
System.out.println("You are granted with Admin Acess!");
rs.close();
}
else if ((usernamea.equals(username2) && (passworda.equals(password2))))
{
System.out.println("Login Success! Welcome Guest User!");
rs.close();
}
I'm not quite sure what you are asking, nor am I sure how the code you posted actually relates to what you are asking.
When you say "you want the 2nd entry", I am assuming you mean the 2nd record in the SQL table.
try(Connection conn = DriverManager.getConnection(url, username, password)){
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
rs.next();
//All data stored in the ResultSet obj, to which you may loop through & select rows of interest. Particularly useful methods are .getMetaData(), .getRow(), etc.
}
Hopefully this is what you are asking for.
If you already have a ResultSet rs, you can call rs.next(). For Example some Code:
if (rs.next())
{
s.name = rs.getString(1);
s.creator = rs.getString(2);
s.dbname = rs.getString(3);
s.tsname = rs.getString(4);
s.cardf = rs.getFloat(5);
s.npages = rs.getInt(6);
s.statstime = rs.getString(7);
s.avgrowlen = rs.getInt(8);
}
Considering your code:
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
String username1 = rs.getString ("USERNAME");
String password1 = rs.getString ("PASSWORD");
String aname1 = rs.getString ("a_name");
rs.next();
String username2 = rs.getString ("USERNAME");
String password2 = rs.getString ("PASSWORD");
String aname2 = rs.getString ("a_name");
Now you can check both the first entry and the second.
Nevertheless, the better practice is to create a user object, save username, password and aname in it.
Then, using some loop, you can go through the entire result set and get all the information from it.
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUsername(rs.getString ("USERNAME"));
user.setPassword(rs.getString ("PASSWORD"));
user.setAname(rs.getString ("a_name"));
userList.add(user);
}
I am creating an SQL that stores information about customers, and want all the customers to have unique contact numbers, essentially as an identifier for themselves. However my validation for my SQL seems to run even if the number already exists within the SQL, and am unsure of what is going wrong.
public static boolean uniqueValidation(String contactNum){
Connection c = null;
Statement stmt = null;
boolean result = true;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:custInfo.db"); //this is telling the code where to retrieve the data from that it is looking for.
stmt = c.createStatement();
String sql = "SELECT rowid AS isFound FROM CUSTINFO WHERE CONTACTNUMBER LIKE "+contactNum+""; //collecting a rowid from custinfo, if the number is found anywhere
ResultSet rs = stmt.executeQuery(sql);
String compareString = rs.getString("isFound"); //setting the value from the resultset of rowid to comparestring
if(!compareString.isEmpty()){ //if there is a value return false
result = false;
}else{
result = true; //else return true as there is no value
}
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return result;
}
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'm getting this error:
java.sql.SQLException: ResultSet not open. Operation 'next' not
permitted. Verify that autocommit is off.
when I'm trying to create instances from a db.
Current code:
try
{
connection.setAutoCommit(false);
stmt = connection.createStatement();
results = stmt.executeQuery("SELECT * from animalTable");
int AnimalCat = -1;
System.out.print(connection.getAutoCommit());
//getting error on line below
while(results.next())
{
int ID = results.getInt(1);
int Age = results.getInt(2);
String Name = results.getString(3);
String AType = results.getString(4);
String Breed = results.getString(5);
AnimalCat = results.getInt(6);
int Adoption = results.getInt(7);
String Gender = results.getString(8);
String Description = results.getString(9);
if(Gender == "Male"){
gen = true;
}
animal = new Animal(Age, AType, gen, Breed, Description, Name);
animalList.add(animal);
if(AnimalCat != -1){
ResultSet resultCat = stmt.executeQuery("SELECT * from CategoryTable where ID = " + AnimalCat);
//without this line below i get a cursor error
resultCat.next();
System.out.println(resultCat.getInt(1) +"\n\n " + resultCat.getString(2));
String Category = resultCat.getString(2);
if(Category == "Lost"){
Date input = resultCat.getDate(3);
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
ResultSet personData = stmt.executeQuery("SELECT * from PersonTable where ID = " + resultCat.getInt(4));
Person person = new Person(personData.getString(2), personData.getString(3), personData.getString(4), personData.getString(5));
Category lost = new Lost(date, resultCat.getString(5), person);
animal.setAnimalCat(lost);
personList.add(person);
}
}
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
I have tried turning off auto commit like it says in the exception and also adding a finally block and closing the statement. From what I can see online that fixed others issues but no luck with mine.
I know the resultCat.next(); is behind the error somehow but I get an "Invalid cursor state - no current row" without it
You have a Statement, obtain a ResultSet from the statement, then obtain another ResultSet. This automatically closes the first ResultSet:
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
So when you call next on the first ResultSet an exception is raised. The Javadoc also tells you what to change: Create a second statement and use that to obtain the second ResultSet.
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");
}