ResultSet is closed, only prints the first "SUBKATEGORI" - java

Im running the code and keep getting the Resultset is closed, is there something wrong with the loops? The Strings that is taken from the for() has multiple "SUBKATEGORIER" aswell. Pls help me I'm new to Java.
Object[] valt = jList1.getSelectedValues();
for (Object ettVal : valt) {
String enSuperkategori = ettVal.toString();
System.out.println(enSuperkategori);
try {
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT SUBKATEGORIID FROM
SUBKATEGORI JOIN SUPERKATEGORI ON SUPERKATEGORI.SUPERKATEGORIID =
SUBKATEGORI.SUPERKATEGORI WHERE SUPERKATEGORI.SKNAMN ='" + enSuperkategori
+"'");
while(rs2.next());
{
PreparedStatement ps2 = connection.prepareStatement("INSERT
INTO ANVANDARE_SUBKATEGORI (ANVANDARE,SUBKATEGORI) VALUES(?,?)");
ps2.setString(1, angivetAnv);
ps2.setInt(2, rs2.getInt("SUBKATEGORIID"));
System.out.println(rs2.getInt("SUBKATEGORIID"));
ps2.executeUpdate();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}

I don't know the exact cause of the error, but my guess is that your first result set is getting closed as soon as you run the inner insert. The good news is that you may run your entire insert using the following single query:
INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI)
SELECT SUBKATEGORIID, SUBKATEGORIID
FROM SUBKATEGORI s
INNER JOIN SUPERKATEGORI sp
ON sp.SUPERKATEGORIID = s.SUPERKATEGORI
WHERE sp.SKNAMN = ?
Your relevant Java code:
String sql = "INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI) ";
sql += "SELECT SUBKATEGORIID, SUBKATEGORIID ";
sql += "FROM SUBKATEGORI s ";
sql += "INNER JOIN SUPERKATEGORI sp ";
sql += "ON sp.SUPERKATEGORIID = s.SUPERKATEGORI ";
sql += "WHERE sp.SKNAMN = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, enSuperkategori);
ps.executeUpdate();

Related

How can I only get 1 element from a SQL Database?

I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE
Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.

I have written this code for fetch record from my table name is owners... but some error is occurs... is there something missing?

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystationary", "root", "");
Statement stmt = con.createStatement();
String qry;
qry = "select * from owners where usernm='" + jTextField1.getText() + "',password='" + jTextField2.getText() + "'";
ResultSet rs = stmt.executeQuery(qry);
while (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
} catch (HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
You have to use PreparedStatement instead to avoid any syntax error or SQL Injection:
try (PreparedStatement ps = con.prepareStatement(
"select * from owners where usernm = ? and password = ?")) {
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
ResultSet rs = ps.executeQuery(qry);
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
}
Your real problem is with the , when you want to use where you have to use and not ,
qry = "select * from owners where usernm='"+jTextField1.getText()+"', password='"+jTextField2.getText()+"'";
//------------------------------------------------------------------^
Instead you have to use :
qry = "select * from owners where usernm='"+jTextField1.getText()+"' and password='"+jTextField2.getText()+"'";
//-------------------------------------------------------------------^^^
But PreparedStatement is more secure.
Another thing, if you want to check for one use, then you can use if (rs.next()) instead of while (rs.next())
On this line:
qry = "select * from owners where usernm='"+jTextField1.getText()+"',password='"+jTextField2.getText()+"'";
You are using a comma to separate your conditions when you should be using the SQL operator "AND."
qry = "SELECT * FROM owners WHERE usernm='"+jTextField1.getText()+"' AND password='"+jTextField2.getText()+"'";
Also, as Dave Newton pointed out, this code is vulnerable to SQL injection. And your while loop after the executeQuery() call doesn't actually use your result set.

Java - Sql query with Alias

I want to retrieve a particular column from the database. For a simple Select statement, I can able to able to retrieve a column like below
public String getDbColumnValue(String tableName, String columnName, String applicationNumber) {
String columnValue = null;
try {
PreparedStatement ps = null;
String query = "SELECT " + columnName + " FROM " + tableName +
" WHERE ApplicationNumber = ?;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString(columnName);
return columnValue;
}
}
catch (Exception ex) {
}
return columnValue;
}
But, I'm using alias in my query like below. And this query works fine. How to use this in Java to retrieve a particular column
select S.StatusDesc from application A, StatusMaster S
where A.StatusMasterId = S.StatusMasterId and A.ApplicationNumber = '100041702404'
Any help would be greatly appreciated!
I think you are confusing simple aliases, which are used for table names, with the aliases used for column names. To solve your problem, you can just alias each column you want to select with a unique name, i.e. use this query:
select S.StatusDesc as sc
from application A
inner join StatusMaster S
on A.StatusMasterId = S.StatusMasterId and
A.ApplicationNumber = '100041702404'
Then use the following code and look for your aliased column sc in the result set.
PreparedStatement ps = null;
String query = "select S.StatusDesc as sc ";
query += "from application A ";
query += "inner join StatusMaster S ";
query += "on A.StatusMasterId = S.StatusMasterId ";
query += "and A.ApplicationNumber = ?";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString("sc");
return columnValue;
}
Note: I refactored your query to use an explicit inner join instead of joining using the where clause. This is usually considered the better way to write a query.

Using variables to create SQL statements

I'm trying to make a sql query builder type program that uses user input data to build custom queries for the table
so far i have
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
// preparedStmt.setString (2, t2);
// preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
So it connects and everything fine but it doesnt execute the query saying something wrong with the sql syntax for values(?,?,?)
Any help would be awesome thanks guys!!
Carl
Try this, Changes in query and in setting prepared statement parameters,
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between ? and ?"
+ "AND id = ?";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
preparedStmt.setString (2, t2);
preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
Share the exact error if doesn't work for you.
Change this:
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
According to the database syntax that you are using. For example if you using a webserver with Mysql go and type the query to see where the typo is. (if you using mysql it needs dancers to every table)
First, you seem to have edited this method many times to try fix the problem, which has left it in a confused state.
remove the "values (?)" from the sql statement, it does not belong here, it seems to be left over from a prepared insert statement.
call preparedStmt.executeQuery() with zero arguments, you have already supplied it with the sql string and only call it ONCE, you assign a value to rs twice.
your sql statement should contain exactly three question marks, try
select count(*) from dancers where ts between ? and ? and id = ?
next call preparedStmt.setString() three times to supply values t1, t2 and id.
Also, remember to close the connection object in the finally block.

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

Categories