Nested SELECT Query Java + MySQL - java

I'm trying to get data from DB.
I must use to queries.
From the first query (In Loop) I get the code of Work codew and the I use it in the second query to get names.
Here's the code works without errors.
The first query fetch rows but the second is not executed.
int i=0;
c= new Connect().getCon();
try{
java.sql.Statement st = c.createStatement();
String sql= " SELECT distinct(s.codew), title, nberstat, desc_w, dated,datef" +
" FROM work w, employe e, stat s " +
" WHERE w.codew=s.codew " +
" and s.idemploye= e.idemploye " +
" and stat_w=0 " +
" and w.idcreator= 1";
System.out.println(sql);
ResultSet res = (ResultSet) st.executeQuery(sql);
String allW ="";
while (res.next())
{
String codew = res.getString("codew");
String title = res.getString("title");
String desc_w = res.getString("desc_w");
String dated = res.getString("dated");
String date = res.getString("datef");
int nberstat = res.getInt("nberstat"); String strnberstat = Integer.toString(nberstat);
///////////////////////////////////
try
{
java.sql.Statement st2 = c.createStatement();
q="SELECT distinct (name), lname From stat s, employe e WHERE codew LIKE '"+codew+"'";
ResultSet res2 = (ResultSet) st2.executeQuery(q);
while (res2.next())
{
String name = res.getString("name");
String lname = res.getString("lname");
allW = name + " "+lname+", "+allW;
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
/////////////////////////////
........
}
c.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
I get this in the console for the second query! SQL code does not execute.
Thanks in advance.
Best regards,
Ali

First of all you should use PreparedStatement with sql parameters "?" to prevent Sql injections.
Secondly, you are using the wrong statement in the second loop. You should be using res2 not res.
This should be:
String name = res2.getString("name"); //not res
String lname = res2.getString("lname"); //not res
Thirdly, you should add a finally{} block and close your connection.

Related

Java PreparedStatement doesn´t set value

I´m totally new to Java and I try to set up a little test to read some data from a MSSQL-database. I have to pass some values to the query but that does not work properly, if I set them manually it works, in my case with the PreparedStatement and the .setLong-Method it does not work.
public class db_testClass {
public static void main(String[] args) throws ClassNotFoundException {
long firstId = 0;
long lastId = 201801001010010403L;
PreparedStatement statement;
int counter = 1;
String SQL = "IF OBJECT_ID('tempdb..#tmpDaten') IS NOT NULL
" DROP TABLE #tmpDaten;
" SELECT DISTINCT
" RIGHT(10000000 + ISNULL(r.xxx, 0), 7) AS Wert
" INTO #tmpDaten
" FROM dbo.xxx
" WHERE r.xxxx BETWEEN firstId = ? AND lastId = ?;
" SELECT DISTINCT
" 'xxxx' AS Art ,
" t.xxx
" FROM #tmpDaten
" LEFT JOIN xxxxxxx a ON a.xxxx = t.xxxx
" AND a.ART = 'xxxx' " +
" WHERE a.xxxx IS NULL;";
String connectionUrl = "jdbc:sqlserver://xxxxxx:1433;databaseName=xxxxxx;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection con = DriverManager.getConnection(connectionUrl);
statement = con.prepareStatement(SQL);
statement.setLong(1, firstId);
statement.setLong(2, lastId);
System.out.println(statement);
ResultSet rs = statement.executeQuery();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
The error says that there is wrong syntax nearby the '='......
Anyone any ideas?
Thanks,
Daniel
Your usage of the BETWEEN operator is suspicious and probably just an outright syntax violation. It should be something like:
something BETWEEN low-value AND high-value
to test if the something lies between the values low-value and hi-value.

Java ResultSet Skipping Records

After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.
Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}
Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.

looping error in java

When I run this code, the code shows errors. Please help me to fix this problem.
Here is my Java code:
public void kirim(){
try{
koneksi();
String data ="select count(Number) from pbk";
ResultSet rs1 = cn.executeQuery(data);
while (rs1.next()){
rs1.getString(1);
}
int banyakData=Integer.parseInt(rs1.getString(1));
for (int i=0; i<=banyakData ;i++){
String sqi = "select Number from pbk";
ResultSet rs = cn.executeQuery(sqi);
while(rs.next()){
rs.getString(sqi);
}
String sql="insert into outbox (DestinationNumber, TextDecoded, CreatorID) values ("
+ "'"+sqi +"',"
+ "'" + jTextArea1.getText()+ "',"
+ "'1'"
+ ")";
cn.executeUpdate(sql);
} JOptionPane.showMessageDialog(null, "Pesan terkirim");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Pesan gagal terkirim");
System.out.println(e.getMessage());
}
}
Here is stack trace output:
After end of result set
Change your code to
ResultSet rs1 = cn.executeQuery(data);
int banyakData;
while (rs1.next()){
banyakData= rs1.getInt(1);
}
and remove
int banyakData=Integer.parseInt(rs1.getString(1));
With you approach you have already iterated through the resultset and after the completition of the while loop you are again fetching from resultset giving you the error.
And also simply doing rs.getString(sqi); and rs1.getString(1); in a while loop doesnt make any sense if you dint put the result in any variable btw sqi is not a valid parameter.

Java SQL (JDBC) : how to move to the next column?

I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.

Java mysql, Simple update with PreparedStatement has syntax error

This code has some sort of simple syntax error. I've fought it for hours now and I give up. Can you spot it? I bet it's easy. Thanks!
When I update just the firstname John, no problem.
When I try to update the commented out line for the lastname too, syntax error.
import java.sql.*;
public class UpdateTester {
public static void main(String[] args) {
try {
Connect connect = new Connect();
Connection connection = connect.getConnection();
try {
String sql = "UPDATE student SET firstName = ? "
+ " WHERE studentID = 456987";
//String sql = "UPDATE student SET firstName = ? "
// + " Set lastName = ?, "
// + " WHERE studentID = 456987";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, "John");
//pst.setString(2, "Johnson");
pst.executeUpdate();
System.out.println("Updated Successfully!");
connection.close();
} catch (SQLException e) {
System.out.println("Exception 1!");
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception 2!");
e.printStackTrace();
}
}
}
Column names are correct.
Updating just the lastname on it's own works correctly too.
Update fails with syntax error when trying to do both, as in the commented out lines.
3 issues:
The SET keyword can only appear once in an UPDATE statement:
Comma before second parameter missing
Unnecessary comma before where clause
The corrected syntax:
String sql = "UPDATE student SET firstName = ?, "
+ " lastName = ? "
+ " WHERE studentID = 456987";
SQL Reference

Categories

Resources