how to count with database statement by using netbeans - java

I'm trying to count the input and match it with the data field in database then count the status and display the number of books that the input had borrowed.
Statement statement = conn.createStatement();
String sql = "SELECT COUNT(jtfMemberID.getText()) as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
ResultSet rs1 = statement.executeQuery(sql);
int personCount = 0;
if(rs1.next()) {
personCount = rs1.getInt("num");
jlbBookBorrow.setText(rs1.getString(personCount));
}else{
jlbBookBorrow.setText("0");
}

The text jtfMemberID.getText() will be interpreted literally in your SQL String. You need to extract it out:
String sql = "SELECT COUNT(" + jtfMemberID.getText() + ") as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
Also, to protect against SQL Injection attacks, consider using PreparedStatement.

Related

How to insert a scanned value on a mySQL table?

I have an issue on how to insert a value from another table into a new one. I have the following code:
Scanner scanner1 = new Scanner(System.in);
java.sql.Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM flight");
int f_id = scanner.nextInt();
int air_id = scanner.nextInt();
while (res.next()) {
if (Integer.parseInt(res.getString("air_id")) == air_id && Integer.parseInt(res.getString("f_id")) == f_id) {
if (Integer.parseInt(res.getString("f_status_f_id_s")) > 0) {
System.out.println("You can reserve");
stmt=(Statement) conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,;
stmt.executeUpdate(query1);
To be more specific on the line String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,; I want the air_id to be the value I scanned before such as f_id. Is this the right syntax way to do it?
Use Prepared Statements to that .i.e:
PreparedStatement stmt= con.prepareStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
//put ?(no of values you need to insert)
String query1= "INSERT INTO reservations values(?,?,?)";
stmt.setInt(1,1);//1 specifies the first parameter in the query
stmt.setString(2,"6/6/2020");
stmt.setInt(3,air_id);//pass your variable
stmt.executeUpdate(query1);
You can insert the variable in your query by using the following code:
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id=#air_id+"(..,..,;
Thank you, I hope it helps you

Can't get my jsp to store the integer value from my result set

All I am trying to do is pull the integer value from the cell. When I run the command in my sql workbench I get the proper value screenshot of db output however when I execute the code in programming environment I get "An exception occurred processing [/registration.jsp] at line [24]" which is this line idnum = rs.getInt("MAX(idnum)")+1; The program has an initial html page where the use enters the desired password, first name and last name. it then sends the info to the jsp which is supposed to take that information increment the user id by 1 from whatever the highest value is currently then create a new table entry with said information.
int idnum = 0;
String pwd = request.getParameter("pwd");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment2", "root",
"has the actual password in the code");
Statement stmt = conn.createStatement();
String query = "SELECT MAX(idnum) FROM users";
ResultSet rs = stmt.executeQuery(query);
idnum = rs.getInt("MAX(idnum)")+1;
Replace
idnum = rs.getInt("MAX(idnum)")+1;
with
if (rs.next())
idnum = rs.getInt(1)+1;
Note that without calling the next() method, the result set pointer/cursor will not move to the 1st row (from default position).
This should work:
String query = "SELECT MAX(idnum) as maxNum FROM users";
ResultSet rs = stmt.executeQuery(query);
if(rs.next(){
idnum = rs.getInt("maxNum")+1;
}

Oracle query execution error [duplicate]

I'm having an issue with my query not working. This is the command variable.
When it executes it should be retrieving the tuples that have BSc as their degree. I have tested this in oracle directly and the query returns these. It is identical to the command statement.
When I print out command, the line looks exactly the same as my command that worked in oracle.
SELECT distinct fname, lname, student_id FROM student where degree='BA';
Yet, it should be printing out to the screen. The tables are loaded into oracle already.
I've been racking my brain with this issue but can't seem to find a fix!
The error I keep getting is:
ORA-00911: invalid character
What I do is I store in degree the result from scanner which is a string. So concatenating it in the command variable shouldn't make an issue -- the query looks identical to what works in oracle.
Could it be because it wants a char instead of a string? If it does, then how would I get it to make "BSc" as a char? Concatenating chars sounds dumb.
Relevant code below:
private String getDegree() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter degree code (either BA or BSc)");
return scan.next();
}
//get the degree name
String degree = getDegree();
//get statement and execute appropriate select
Statement stmt = con.createStatement();
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
System.out.println(command);
ResultSet result = stmt.executeQuery(command);
//determine number of columns
ResultSetMetaData metadata = result.getMetaData();
int columns = metadata.getColumnCount();
//print heading
System.out.println("\nFNAME LNAME STUD_ID");
System.out.println("====================================");
//loop through result and print columns
while (result.next()){
for (int i=1; i <=columns; i++){
System.out.print(result.getString(i)+spaces(15-result.getString(i).length()));
}
System.out.println();
}
`
In JDBC your SQL statement should not be terminated by semicolon.
Change
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
to
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "'";

Add values from JSP to another table in MySQL

I am trying to add a few details to a table named questionpaper from my front end JSP and from another table named questions.
In table questionpaper I have a column named ExamID to which I have to add a value of ExamId column from another table named question. This ExamId value has to be added simultaneously with the data added from the JSP page. The data from the JSP page is getting added without any error but the ExamId cannot be added simultaneously.
public int QuestionPaper(Questions paramQues) {
// TODO Auto-generated method stub
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,NegMarks,ExamId)values(?,?,?,?,?,?,?,?,?)";
int status=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineexam", "root", "admin");
PreparedStatement stat1 = con.prepareStatement(query);
if((paramQues.getAns1()!=null)&&(paramQues.getAns2()!=null)&&(paramQues.getAns3()!=null)&&(paramQues.getAns4()!=null)&&(paramQues.getMarks()!=null)&&(paramQues.getNegM()!=null)&&(paramQues.getQues()!=null))
{
System.out.println("implementation "+paramQues.getOption());
System.out.println("Marks-->"+paramQues.getMarks());
System.out.println("Ans->>"+paramQues.getAns1());
stat1.setString(1,paramQues.getQues());
stat1.setString(2,paramQues.getAns1());
stat1.setString(3,paramQues.getAns2());
stat1.setString(4,paramQues.getAns3());
stat1.setString(5,paramQues.getAns4());
stat1.setString(6,paramQues.getOption());
stat1.setInt(7,paramQues.getMarks());
stat1.setInt(8,paramQues.getNegM());
System.out.println("Ans->>"+paramQues.getAns1());
String query2="SELECT * FROM questions ORDER BY ExamId DESC LIMIT 1";
PreparedStatement stat2 = con.prepareStatement(query2);
ResultSet rs1 = stat2.executeQuery(query2);
Integer Examid= rs1.getInt("ExamId");
System.out.println("exam id-->"+Examid);
stat1.setInt(9,Examid);
stat1.executeUpdate();
Integer TotalQues= rs1.getInt("TotalQuestions");
String query3="SELECT * FROM questionpaper ORDER BY PaperId DESC LIMIT 1";
PreparedStatement stat3 = con.prepareStatement(query3);
ResultSet rs2 = stat3.executeQuery(query3);
Integer PaperId= rs2.getInt("PaperId");
if(PaperId<=TotalQues)
status=1;
else
status=0;
}
}
catch (Exception e)
{
System.out.println("Exception in FacultyTry->" + e);
}
return status;
}
Output:
Answer:l
j
d
d
options-->o3
Marks-->2
NegMarks-->1
implementation o3
Marks-->2
Ans->>l
Ans->>l
Exception in FacultyTry->java.sql.SQLException
You have mentioned, your tables contain ExamID column & you are using ExamId in SQL query. Either of the below query contains wrong column name.
Your SQL query :
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,
NegMarks,ExamId)values(?,?,?,?,?,?,?,?,?)";
OR
String query2="SELECT * FROM questions ORDER BY ExamId DESC LIMIT 1";
Required SQL Query :
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,
NegMarks,ExamID)values(?,?,?,?,?,?,?,?,?)";
OR
String query2="SELECT * FROM questions ORDER BY ExamID DESC LIMIT 1";
In your code you don't need to prepare a statement that has no parameters denoted by ?.
Use the statement to execute query
ResultSet rs1 = stat1.executeQuery(query2);
or
Statement stat2 = con.createStatement();
ResultSet rs1 = stat2.executeQuery(query2);

How to use user input as parameter for query?

So I'm very new to java and SQL and they are my first programming languages. I am trying to do some work with JDBC. I want to allow for a user to input an id and return a query based on the variable. If someone could at least point me in the right direction... Here is the code I'm starting with. Mind you its crude but just trying to get a working piece of code so I can better implement it in my main class.
Scanner input = new Scanner(System.in);
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Derek\\Documents\\Databases\\example.sqlite");
Statement stat = conn.createStatement();
PreparedStatement prep1 = conn.prepareStatement(
"insert into MedType values (?, ?);");
PreparedStatement prep2 = conn.prepareStatement(
"insert into Media values (?, ?,?, ?,?, ?);");
System.out.print("Please choose a database(MedType or Media): ");
String db=input.next();
if(db.equalsIgnoreCase("MedType"))
{
System.out.print("Enter in ID: ");
String answer1 = input.next();
System.out.print("");
String answer2 = input.nextLine();
System.out.print("Enter in Description: ");
String answer3 = input.nextLine();
prep1.setString(1, answer1);//add values into cell
prep1.setString(2, answer3);
prep1.addBatch();//add the columns that have been entered
}
conn.setAutoCommit(false);
prep1.executeBatch();
prep2.executeBatch();
conn.setAutoCommit(true);
System.out.print("Please Enter Query(One or All): ");
String q=input.next();
ResultSet rs= stat.executeQuery("select * from MedType;");
if(q.equalsIgnoreCase("all")){
while (rs.next()) {
System.out.print("All ID = " + rs.getString("ID") + " ");
System.out.println("All Description = " + rs.getString("Description"));}
}
if(q.equalsIgnoreCase("one")){
System.out.print("Enter ID: ");
}
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+ (rs.getString("ID")+"="+idNum));
if(q.equalsIgnoreCase("one")){
while (oneRs.next()) {
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
rs.close();
oneRs.close();
conn.close();
}
}
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+
(rs.getString("ID")+"="+idNum));
This is where I'm having trouble. Creating a statement that says return something from the table if its id is equal to the user input. I get this error
Exception in thread "main" java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "=": syntax error)
In query you are trying to access single row by passing id.. In generally sql query we are using to access single row by passing some information. select * from MedType where id=3 this query will return you result set containing row or rows with id equals to 3.
so in your code your query should be select * from MedType where id="+idNum+" if in your db id column is int.
and keep this query in if block only i.e
if(q.equalsIgnoreCase("one"))
{
System.out.print("Enter ID: ");
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where id="+idNum+" ");
// if id column in db is int if it is string then use id='"+idNum+"'
while (oneRs.next())
{
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
In your query:
select * from MedType Where"+ (rs.getString("ID")+"="+idNum
you seem to try to grab the ID from the first resultset where you return all tuples.
That won't work as in the where clause the ID won't be there (as there is no result right now without rs.next()). If there was a result then you potentially have something like 'where 3 = 3' (3 would be the result of the previously returned value. Have you tried simply to use:
select * from MedType Where ID = " + idNum
Hope that makes sense.

Categories

Resources