Parameterized inner join - java

I have two tables named mytest and class what I need to do is to join them by the column id that exists in both table, but the problem is that I need to firstName column be parametrized in order to join the selected firstName, not all the columns that have the same id with fristName column this is the point I got but I have an error
SELECT mytest.firstName,class.name
FROM mytest
INNER JOIN class ON mytest.id=class.id
where fristName=?
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 '?' at line 1``
public List <studentrgister> showcourse(String names) throws Exception {
List<studentrgister> students = new ArrayList<>();
String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
System.out.println("loding the driver");
Statement s=null;
studentrgister mystudent=null;
Connection myConn = null;
myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
System.out.println("username and password is correect");
PreparedStatement myStmt=null;
ResultSet myRs = null;
String name=names;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver is loaded");
String sql="SELECT mytest.firstName,class.name FROM mytest INNER JOIN class ON mytest.id=class.id where mytest.firstName=? " ;
s =myConn.createStatement();
s.executeQuery(sql);
myRs=s.getResultSet();
if (myRs.next()) {
String classname = myRs.getString("name");
int numbername=myRs.getInt("firstName");
mystudent = new studentrgister(classname,numbername);
students.add(mystudent);
}
else {
throw new Exception("Could not find student id: " );
}
return students;
}
finally {
close(myConn,myStmt,null);
}
}

If you want to use parameters in a SQL statement, you need to use a PreparedStatement. For example:
String sql = "SELECT mytest.firstName,class.name FROM mytest "
+ "INNER JOIN class ON mytest.id=class.id "
+ "where mytest.firstName = ? " ;
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, "Anne"); // we apply the parameter value
ResultSet rs = ps.executeQuery();
while (rs.next()) {
...
}

Related

why I cannot sum all number between two rows?

I am trying to write a code that sum all the data in a column named AMOUNT between two rows in a column named DATA in a table named PERSON and I used the sum function and I use between function
and I got the following error:
java.sql.SQLSyntaxErrorException: Syntax error:
Encountered "BETWEEN" at line 1, column 45.
the code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT " +
"FROM PERSON BETWEEN DATE=? AND DATE=?";
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices",
"user1", "password");
ps = con.prepareStatement(sql);
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
rs = ps.executeQuery();
if (rs.next()) {
String sum = rs.getString("sumAmount");
jLabel3.setText(sum);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
Try something like this:
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT FROM PERSON " +
"WHERE (col_name) between '2020-05-01 00:58:26' " +
"and '2021-06-18 19:53:17'";

Multiple Statement in single connection

I wrote code to run multiple statement in single connection. The first statement will retrieve IDs to be looped and used by the second statement then get the desired output. As example:
String sql1 = "SELECT ID FROM __TestParent WHERE Status = 'S'";
try (
Connection conn = DbConnector.getConnection();
Statement s = conn.createStatement();
Statement s2 = conn.createStatement();
ResultSet rs = s.executeQuery(sql1)
) {
while(rs.next()) {
String id = String.valueOf(rs.getInt("ID"));
String sql2 = "SELECT Description FROM __TestChild WHERE FK = " + id;
try (
ResultSet rs2 = s2.executeQuery(sql2)
) {
while(rs2.next())
Util.printLog("INFO",rs2.getString("Description"));
}catch(SQLTimeoutException sqltoex){
Util.printLog("SEVERE",sqltoex);
}catch(SQLException sqlex){
Util.printLog("SEVERE",sqlex);
}
}
}catch(SQLTimeoutException sqltoex){
Util.printLog("SEVERE",sqltoex);
}catch(SQLException sqlex){
Util.printLog("SEVERE",sqlex);
}
Util.printLog method is to print the message in the desired format
The code run perfectly fine and the output was as expected. What I want to know is:
Is this the right way to do it, or is/are there better way to write the code.
Is there anything that I need to be aware of? Because I seems cannot find anything about this use case other than this link Multiple-statements-single-connection from CodeRanch which is 16-year-old thread and I'm not quite clear other than driver support.
Thanks.
You can actually do what you want using a single query and result set:
SELECT c.Description
FROM __TestChild c
INNER JOIN __TestParent p
ON c.FK = p.ID
WHERE p.Status = 'S';
Code:
String sql = "SELECT c.Description FROM __TestChild c ";
sql += " INNER JOIN __TestParent p ON c.FK = p.ID ";
sql += "WHERE p.Status = 'S'";
try (
Connection conn = DbConnector.getConnection();
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql)
) {
while(rs.next()) {
Util.printLog("INFO", rs.getString("Description"));
}
} catch(SQLTimeoutException sqltoex) {
Util.printLog("SEVERE",sqltoex);
} catch(SQLException sqlex) {
Util.printLog("SEVERE",sqlex);
}

sql for update "ERROR: column "used" of relation "account" does not exist" even though it does

I have used this method without using the join in the query and it was working as expected. But I added a inner join and now it can't update the "used" column
public HashMap<String, Comparable> getPhoneNumberAndMarkAsUsed() {
String[] colNames = { "phone_number.id", "phone_number.phone_number",
"phone_number.account_id", "phone_number.used AS used",
"(now() AT TIME ZONE account.timezone)::time AS local_time" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";
HashMap<String, Comparable> account = new HashMap<String, Comparable>();
try (Connection conn = DriverManager.getConnection(url, props); // Make sure conn.setAutoCommit(false);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
conn.setAutoCommit(false);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
// Get the current values, if you need them.
account.put("phone_number", rs.getString("phone_number"));
account.put("account_id", rs.getLong("account_id"));
rs.updateBoolean("used", true);
rs.updateRow();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
the loop prints the following
7223 id, 10001234567 phone_number, 1093629 account_id, f used, 23:32:42.502472 local_time
accourding to the output above, then I am use that column "used" is part of the ResultSet. But I get the following Exception
org.postgresql.util.PSQLException: ERROR: column "used" of relation "account" does not exist
This is the query when printed
select phone_number.id, phone_number.phone_number, phone_number.account_id, phone_number.used AS used, (now() AT TIME ZONE account.timezone)::time AS local_time from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update
used belongs to the phone_number table not the account table. How can this be resolved?
here is the problem in your code:
rs.updateBoolean("used", true);
this statement will try to update the data of table through resultset but to do that you cannot user join and also there is one problem.
As you are updating via resultset it will try to update account table and if we find used column is account table then error occurs.
so your code is trying to find column "used" in account table but it is not there.
try this one:
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from phone_number INNER JOIN account phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";

Getting SQL exception in where clause while inserting data in database through java

I want to store the password for required ID using java. Everything is working fine except that I am getting this Exception
"SQL Exception thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(Pass_word) set Pass_word = 'pass' where ID = 2' at line 1".
I am getting this exception only in update query but not in select query.I am using Eclipse. Can anyone tell me what I am doing is wrong?
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class information {
public static void main(String[] args) {
String password;
ResultSet rs;
String queryString;
int x=1;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
System.out.print("Database is connected !");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = null;
while(x==1)
{
System.out.println("Press 1 to enter student id");
System.out.println("Press 2 to exit");
Scanner s= new Scanner(System.in);
int choice = s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter the ID of student");
int id = s.nextInt();
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID=" +id;
rs= stmt.executeQuery(queryString);
//System.out.println(rs.getInt("ID"));
while(rs.next())
{
if(rs.getInt("ID")== id)
{
String roll = rs.getString("Roll_no");
String date = rs.getString("Date");
String time = rs.getString("Time");
String c_name = rs.getString("Course_name");
String c_code = rs.getString("Course_code");
password pass1= new password(roll,date,time,c_name,c_code);
pass= pass1.passwd();
System.out.println(pass);
queryString =" Update student_reg(Pass_word) set Pass_word = 'pass' where ID = ?";
//queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = ?";
//stmt.executeUpdate(queryString);
//PreparedStatemenet pstmt = conn.preparedStatement("INSERT INTO student_reg(Password) VALUES ('password') where ID = ?");
//pstmt.setLong(1, id);
pstmt = conn.prepareStatement(queryString);
pstmt.setInt(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
s.close();
}
}
break;
case 2: x=0;
}
}
if(conn!= null)
{
stmt.close();
pstmt.close();
conn.close();
conn = null;
}
}
catch(ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
catch(SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch(Exception e)
{
System.out.print("Do not connect to DB - Error:"+e);
}
}
}
Your code has many problem:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
This line you have condition where but you not set the value yet, you should set
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Better if you take a look at PreparedStatement for prevent SQL Injection as well.
The last one:
queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = id";
This line seem you want to update something. Please review it.
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
should be
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
This would fix the error, but it would be better to use a PreparedStatement, where the query String looks like "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = ?", and you pass the id as a parameter.
It is so obvious because you shouldn't include the 'id' in your query string:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Very good hint from #spencer: you can not use WHERE clause in your INSERT INTO statement. Probably you wanted to UPDATE a row with that id. Also it is better to do it using PreparedStatemenet to avoid such mistakes:
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
PreparedStatemenet pstmt = conn.preparedStatement("UPDATE student_reg SET password = 'password' where ID = ?");
pstmt.setLong(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
I suggest you to rename the column name password, because it is a reserved word in mysql, so you may get strange results working with that column name. Change it to some other thing like: pass_word or passwd , ... . As you may know you can use keywords as column names in your queries using some quotes or other things but it is more safe to rename it to another name, just for hint.
if you use this connection without a connection-pool, you may want to close the Statement and the Connection.
Good Luck.

MySQL exception - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I get the error:
'Unknown column 'customerno' in 'field list' '.
But, that column exists in my customer table. Then why am I getting this exception ?
Code:
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
System.out.print(rs.getString("customerno"));
}
} catch(SQLException ex){System.out.println(ex);}
}
}
Look at what your query really is. This:
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
is equivalent to:
static String myQuery = "SELECT customerno, nameFROM customers;";
Now can you see what's wrong? I'm surprised it complained about customerno rather than the lack of a FROM part...
Note that I suspect you don't want the ; either. I'd write it all one one line just for readability, when you can, as well as limiting the accessibility and making it final:
private static final String QUERY = "SELECT customerno, name FROM customers";
the problem with your syntax is that you have no space between name and FROM
String myQuery =
"SELECT customerno, name" + // problem is here
"FROM customers;";
instead add a space after name
String myQuery =
"SELECT customerno, name " + // add space here
"FROM customers";
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
//Try and change this with the numeric value that is present in the database,
e.g if it's column 2 do something like
rs.getString(1);
System.out.print(rs.getString("customerno"));
}
}catch(SQLException ex){System.out.println(ex);}
}
}

Categories

Resources