why we use next() method in java? [duplicate] - java

This question already has answers here:
What does "if (rs.next())" mean?
(7 answers)
Closed 6 years ago.
Here is the code
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\STUD1.accdb");
Statement st = conn.createStatement();
String sql="select Username,Password from SUN where Username='"+user+"'and Password='"+pass+"'";
ResultSet rs=st.executeQuery(sql);
int count=0;
while(rs.next()) {
count=count+1;
}
if(count>0) {
JOptionPane.showMessageDialog(null, "Access granted");
} else if(count<1) {
JOptionPane.showMessageDialog(null,"User Not Found\nAccess is Denied");
}
I am creating a user verification system in Java and I have connected my program with MS Access. I have inserted some records in the fields of table SUN in MS Access and it is working properly. But I just want to know the working of next() method and count variable in my program.

It moves (or tries to, returning a boolean telling whether it succeeded or not) the resultset cursor forward. The count variable is useless, since you can just write if(rs.next()) to determine which message is shown.

Related

How to convert prepared statement into String [duplicate]

This question already has answers here:
Get value from a ResultSet by name
(2 answers)
Closed 1 year ago.
I am trying to set a string value into DB using prepared statement and Result Set. But it inserts into DB row this "com.mysql.cj.jdbc.result.ResultSetImpl#fcd6521"
PreparedStatement check = connection.prepareStatement(
"SELECT buildingName FROM building GROUP BY buildingId HAVING buildingId = ?");
check.setInt(1, building_id);
ResultSet rs = check.executeQuery();
insert.setString(1, String.valueOf(rs));
insert.executeUpdate();
I think that you need to read the tutorial indicated by #user16320675
A ResultSet is a type of set. It has to be accessed like that:
//if you expects receive only one buildName you use a simple if, otherwise you have to use a loop and a list or something like that
String text;
if(rs.next()){
text = rs.getString(0);
}
//index it's related to buildingName

java.sql.SQLException: Closed Resultset: next [duplicate]

This question already has an answer here:
SQLException: the result set is closed
(1 answer)
Closed 3 years ago.
I didn't find the reason for a SQLExeption, I got it at while(dbrs.next()). It is simple, it was working, but after update to Oracle Server 19, I got this error. I got still a result set in Oracle Developer with the same account.
Statement st = conn.createStatement();
if (Oracle){
ResultSet dbrs = st.executeQuery("select table_name from all_tables");
while(dbrs.next()){
if (dbrs.getString(1).equals(G_IN)){
st.execute("DROP TABLE "+G_IN);
System.out.println(G_IN+" gelöscht");
}
}
dbrs.close();
}else{
String loeschen="DROP TABLE IF EXISTS \"" + G_IN +"\"";
System.out.println(loeschen);
st.execute( loeschen );
}
You shouldn't reuse a Statement object as is the case in your while loop. To execute a new query, you need to use a new Statement object.
Replace
st.execute("DROP TABLE "+G_IN);
with
conn.createStatement().execute("DROP TABLE "+G_IN);
and it should work.

Placeholders not working when using SQL statement in Java (JDBC) [duplicate]

This question already has answers here:
Variable column names using prepared statements
(7 answers)
Using Prepared Statements to set Table Name
(8 answers)
Closed 4 years ago.
Very first question here so I apologize for any mistakes and imperfections.
Basically there are three files, my main method tech_supportv1, login_controller containing a class used to store a bunch of methods, and login.java, a javabean.
The point is to check if a certain row exists on the tech_support database. To do so I'm trying to use the code below. (db_util and type are classes containing connection data, they are tested and they work).
ISSUE: the data from the main method seems not be pasted into the string in the appropriate placeholders, and an error is returned. (Of course if I manually enter the strings instead of using placeholders, everything works just fine.)
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''technicians' WHERE 'techID' LIKE 16' at line 1
I tired to look at the mariaDB docs but all the other syntax provided yields the same results.
So this the main method.
public class Tech_support_v1 {
public static void main(String[] args) {
System.out.println("Start.");
login bean = new login();
bean.setTable("technicians");
bean.setColumn("techID");
bean.setID(16);
login_controller.select(bean);
}
}
This is the select method (with bean as argument, login is the Javabean class).
public static boolean select(login bean) {
String sql = "SELECT * FROM ? WHERE ? LIKE ?";
ResultSet rs;
try (
Connection conn = db_util.getConn(db_type.MYSQL);
PreparedStatement stmt = conn.prepareStatement(sql);
) {
stmt.setString(1, bean.getTable());
stmt.setString(2, bean.getColumn());
stmt.setInt(3, bean.getID());
rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("Y");
return true;
} else {
System.err.println("N");
return false;
}
} catch (Exception e) {
System.err.println(e);
return false;
}
}
I won't include the bean class because it's literally only three variables with the relative set/get methods. Also the database runs with MariaDB, and is MySQL.
Thanks to everyone in advance.
You have multiple problems with your code :-)
First, you can't set table or column names with "setString" in a Prepared Statement!
See this Question: How to use a tablename variable for a java prepared statement insert
Second, as Daniel Pereira pointed out: You are trying to use a "like" Statement with "setInt"! See: https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html
You are comparing with LIKE but you are setting an Int. Change the LIKE to = and see if it works.
Try doing something like this:
String sql="SELECT * FROM :table ";
try (
Connection conn = db_util.getConn(db_type.MYSQL);
PreparedStatement stmt = conn.prepareStatement(sql);
)
{
String query = StringUtils.replace(sql, ":table", bean.getTable());
stmt.executeQuery(query);
}

Always getting Run Time Error #Java [duplicate]

This question already has answers here:
Removal of JDBC ODBC bridge in java 8
(5 answers)
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 4 years ago.
So I'm getting run time error always when I tried to login. Below is the code. I'm using Java JRE 8 Eclipse to compile it. Can anyone please let me know what's the problem? I've omitted most of the code. Link to full code : https://codeshare.io/5gNyZw . Already tried Removal of JDBC ODBC bridge in java 8 and how to use JDBC in java 8 but nothing works
try
{
String database="StegoKeys.mdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";PWD=cegospdv";
Connection con=DriverManager.getConnection(url);
String sql="select * from keys";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
if(txtKey.getText().equals(rs.getString("key")))
{
id=rs.getString("uname");
if(txtname.getText().equals(id))
{
int stat=Integer.parseInt(rs.getString("status"));
flag=1;
if(stat==1)
{
button1.setEnabled(true);
button2.setEnabled(true);
btnadminset.setVisible(true);
txtKey.setEnabled(false);
btnLogin.setEnabled(false);
}
else
{
button1.setEnabled(true);
txtname.setEnabled(false);
txtKey.setEnabled(false);
btnLogin.setEnabled(false);
}
}
//System.out.println(id+" in MainStego");
con.close();
break;
}
}
if(flag==0)
{
JOptionPane.showMessageDialog(this,"Invalid User & Key");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,"Run Time Error");

Java JDBC result set error, but why? [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","user","pass");
Statement myStmt1 = myConn.createStatement();
System.out.println("connected");
for(int i=1; i<1375462;i++){
ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);
String Name = myRs1.getString("Name");
System.out.print(i);
System.out.println("Name:"+Name);
}
I'm using JDBC Java to query the name from database but this time it got an error and I don't know why. I have used Java JDBC before. I can connect to database but the query seem like not working? Id column is integer 10 digit.
"run: connected java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5206)"
This kind of error appears when you try to access something without moving cursor. Try to put myRs1.next(); before getting String.
Inside for loop, when getting the ResultSet, you need a check myRs1.next() as described below.
for(int i=0; i<1;i++){
ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);
while(myRs1.next()) {
String Name = myRs1.getString("Name");
System.out.print(i);
System.out.println("Name:"+Name);
}
}

Categories

Resources