How can i execute 2 Select Queries in Java? - java

I need your help there with my code I am working on eclipse. When I try to execute 2 Select Queries in Java it doesn't seem to work , I searched the internet but I couldn't find a solution. I need to execute 2 select because I need data from 2 tables I got in a database.
Table 1: questions
Table 2: selections
Well the first query seems to work fine as I can find my items as I should when I execute. The items from Table 2 throws me an execution that
"Column 'selid' not found. ". // Selid Column is on Table 2.
I am posting you the faulty code on bottom in case you can help me on this.
Thanks in advance.
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String dbName="teddb";
res.setContentType("text/html");
res.setCharacterEncoding("utf-8");
PrintWriter out = res.getWriter();
//String dbUserName="root";
//String dbPassword="root";
try{
String qid = "";
String question = "";
String sel1 = "";
String sel2 = "";
String sel3 = "";
String correct = "";
String selid ="";
String sel="";
Connection dbCon;
Class.forName(driver);
dbCon = DriverManager.getConnection(dbURL);
ResultSet rs;
ResultSet rs2;
Statement stmt;
Statement stmt2;
stmt = dbCon.createStatement();
stmt2 = dbCon.createStatement();
String qry = "";
String qry2 = "";
qry = "select * from questions";
qry2 = "select * from selections";
rs = stmt.executeQuery(qry);
stmt = dbCon.prepareStatement(qry);
rs2 = stmt2.executeQuery(qry2);
stmt2 = dbCon.prepareStatement(qry2);
String[] columns = new String[] { "qid",
"question_text" , "selid" , "selection_text" ,};
Random rn = new Random();
int range = 2 - 1 + 1;
int randomNum = rn.nextInt(range) + 1;
out.println(randomNum);
while (rs.next()) {
for (int i = randomNum; i <= randomNum; i++) {
question = rs.getString(columns[1]);
sel1 = rs.getString(columns[2]);
sel2 = rs.getString(columns[3]);
}
}
PreparedStatement pstmt;
for (int z=1;z<=3;z++){
selid = String.valueOf(rs.getString(columns[2]));
pstmt = dbCon.prepareStatement(qry2 + " where qid = ? and selid ='z'");
pstmt.setString(1, qid);
rs2 = pstmt.executeQuery();
while (rs2.next()) {
for (int i = randomNum; i <= randomNum; i++) {
if (z==1)
sel1 = rs.getString(columns[3]);
else if (z==2)
sel2 = rs.getString(columns[3]);
else
sel3 = rs.getString(columns[3]);
}
}
}
out.println("<!DOCTYPE html>"+
"<html><body>"+
"<form method=\"post\" action=\"demoServlet\">"+
"<b><h1>Ερώτηση</h1></b> <br><br>"+
"<b><h1>"+question+" </h1></b> <br><br>"+
"<b> 1: </b> <input type=\"radio\" name=\"iscorrect\" value=\"" + sel1 + "\"/><br>"+
"<b> 2: </b> <input type=\"radio\" name=\"iscorrect\" value=\"" + sel2 + "\"/> <br>"+
"<b> 3: </b> <input type=\"radio\" name = \"iscorrect\" value=\"" + sel3 + "\"/><br><br>"+
"<br><input type=\"submit\" name=\"submit\" value=\"Απάντηση\"/>"+
"</form></body></html>");
dbCon.commit();
String msg=" ";
rs.close();
rs2.close();
stmt.close();
dbCon.close();
}
catch (Exception e){
out.println(e);
}
Concept is that i have 2 tables and iam making a form that the users answers some questions. Iam executing both tables and then iam trying to put the variables in to the form with submit. DoPost will take effect after DoGet in the same servlet.
Here is the example of the tables.
questions | selections
qid | question | qid | | selid | selection_text |correct
q1 | 1+1? | q1 1 5 0
q1 2 2 1 // true
q1 3 4 0

Change
rs = stmt.executeQuery(qry);
rs2 = stmt.executeQuery(qry2);
to
rs = stmt.executeQuery(qry);//first query
rs2 = stmt2.executeQuery(qry2);//second query

Related

how to resolve error SQL Exception thrown: java.sql.SQLException: Operation not allowed after ResultSet closed [duplicate]

This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 6 years ago.
I am trying to run following code but getting error:
SQL Exception thrown: java.sql.SQLException: Operation not allowed
after ResultSet closed.
How to resolve this error? I need two result sets for my application.
public static void main(String[] args) {
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/test";
String dbUser = "root";
String dbPwd = "Syntel#92";
Connection conn;
ResultSet rs, res1 = null;
Statement stmt = null;
int rowcount = 0;
// String queryString = "create table job_status_table as select j1.job_id,s1.Source_ID,s1.Source_name from JOb_list j1,SOURCE_DETAILS s1 where s1.Source_ID = j1.Source_ID";
String queryString = "create table job_status_table as select source_id,source_name from source_details";
String addcolumn = "alter table job_status_table add column Source_rowcount int";
String fetchdata = "Select Source_name from job_status_table";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
stmt = conn.createStatement();
// get record count from table job_status_table1
// stmt.executeQuery("select count() from job_status_table1");
// create table
stmt.executeUpdate(queryString);
System.out.println("Table created in the database");
stmt.executeUpdate(addcolumn);
System.out.println("alter table");
rs = stmt.executeQuery(fetchdata);
System.out.println("fetch data");
while (rs.next()) {
String table_count = null;
String table_name = null;
table_name = rs.getString("Source_name");
System.out.println(table_name);
// table_name = rs.getString("Source_name");
//System.out.println(table_name);
//rs.close();
table_count = "select count(*) from " + table_name;
//table_count = "select count(*) from " + table_name;
//rs.close();
// res1 = stmt.executeQuery(table_count);
res1 = stmt.executeQuery(table_count);
//System.out.print(res1);
if (res1.next()) {
rowcount = res1.getInt(1);//res1.getInt(1);
System.out.println("Result set values" + rowcount);
} else {
System.out.println("value is not present in resultset");
}
System.out.println("Get Row Count");
System.out.println(table_count);
// int cnt = rcnt(table_count);
String updaterow = "update job_status_table set Source_rowcount ="
+ rowcount
+ " where Source_name = '"
+ table_name
+ "'";
System.out.println("updateoutput" +stmt.executeUpdate(updaterow));
System.out.println("Update Complete");
}
/* if (conn != null) {
rs.close();
res1.close();
stmt.close();
conn.close();
conn = null;
}
*/
}
catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}**
You could try this:
First copy the ResultSet rs in an ArrayList and close it.
Iterate over the ArrayList and close res1 before the update.
And I don't think the else with "value is not present in resultset" is reachable, but if you should set the rowcount to 0.
EDIT
After reading the referenced question the second time:
The problem is the reusing of stmt for res1 and the update

Java MySQL returns only one row

I have this code:
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
System.out.println("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
System.out.println(p);
tasks.add(p);
}
The problem is that it returns only the first row, and if I run the query manually I get more results (16 total). Here's the output:
SELECT * FROM tasks WHERE uid = 4 ORDER BY title ASC
models.Task#164b9b8f
Any idea why this is happening?
May be you can improve the code a bit like below which will help you to quickly identify the issue.
int rowCount = 0;
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
String query = "SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
rowCount++;
System.out.println(rowCount + "." + p);
tasks.add(p);
}
} finally {
System.out.println("Number of records = " + rowCount);
}
In this approach you can clearly identify how many rows were iterated.

Inserting records into a MySQL table using Java

I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

deleterow() ReadOnly Statement error

i'm doing my first applications using JDBC/Oracle...
Today i had a problem and i can't find out what's wrong.
That's my code (some parts)
My global variables:
public class Esercizio02_GestioneDB {
public Esercizio02_GestioneDB(){
}
public Connection conn = null;
public Statement s = null;
public ResultSet rs = null;
public ResultSet rs1 = null;
ResultSetMetaData rsmd = null;
ResultSetMetaData rsmd1 = null;
[...]
My connection method:
public void connetti(String user, String pwd) throws ClassNotFoundException, SQLException {
//DRIVER
Class.forName("oracle.jdbc.driver.OracleDriver");
//URL
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
//CONNECTION
conn = DriverManager.getConnection(url, user, pwd);
//AUTOCOMMIT
conn.setAutoCommit(true);
//STATEMENT
s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
}
So, i have a method to delete a row in a table:
private void eliminaPrenotazione() {
try {
String message1 = "Scegli la prenotazione da cancellare:\n\n";
String query = "SELECT * FROM camere_prenotate";
rs1 = s.executeQuery(query);
rsmd1 = rs1.getMetaData();
message1 += "INDICE ";
for (int i=1; i<=rsmd1.getColumnCount(); i++) {
message1 += rsmd1.getColumnName(i);
message1 += " \t ";
}
message1 += "\n_______________________________\n";
int rowIndex = 1;
String columnType = "";
while (rs1.next()) {
message1 += "["+rowIndex+"]. ";
rowIndex++;
for (int i=1; i<=rsmd1.getColumnCount(); i++) {
columnType = rsmd1.getColumnTypeName(i);
if(columnType.substring(0, 3).equalsIgnoreCase("num")) message1 += rs1.getInt(i);
if(columnType.substring(0, 3).equalsIgnoreCase("var") || columnType.substring(0, 3).equalsIgnoreCase("dat"))
message1 += rs1.getString(i);
message1 += " \t ";
}
message1 +="\n";
}
message1 +="\n";
String scelta = JOptionPane.showInputDialog(null, message1);
int sceltaInt = Integer.parseInt(scelta);
rs1.absolute(sceltaInt);
rs1.deleteRow();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Errore: " + e.getMessage());
}
}
deleteRow() returns me an error... it says me that my ResultSet is read only, but in my statement it's delcared as
s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
so, what's wrong?
sry for the noobish code and the bad english -.-'''
select * makes the Resultset instance readonly.
select COLUMNNAME makes it updatable.

Get Array From List Of Rows?

I was curious on how to get a list of rows and add values from each row to an array in Java.
Here is what it looks like in PHP:
<?php
$result = mysql_query("SELECT * FROM names");
while($row = mysql_fetch_array($result)) {
// Get variables from this row and such
}
?>
I can't seem to find out how to do this in Java.
Resolution Found
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT TOP 10 * FROM SalesLT.Customer");
while (res.next()) {
String firstName = res.getString("FirstName");
String lastName = res.getString("LastName");
System.out.println(" " + firstName + " " + lastName);
}
If you want to use pure JDBC you can follow the example from the JDBC tutorial:
public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection(
"jdbc:myDriver:myDatabase", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
But most people don't do this any more; you can, for example, use an ORM like hibernate to abstract the database a bit.

Categories

Resources