Prepared Statement with SubQuery throwing error [duplicate] - java

I am trying to execute a query that returns a student whose name and last name concatenated equal the search key parameter.
For that I am doing this in my class that manages anything related to the database for my Student class.
When the query is executed I am getting the error that follows:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
What's wrong? I have checked that's the correct way to use concat.
name and lastName are VARCHAR in the mysql database.
public static Student findStudent(String key) {
if (key == null) return null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
String selectSQL = "select * from project.students where concat(name, lastName) = ? ;";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, key);
Student student = null;
rs = preparedStatement.executeQuery(selectSQL);
if (rs.next()) {
StudentDB.setStudentAttributes(student, rs);
}
return student;
} catch(SQLException e) {
e.printStackTrace();
} finally {
close();
try {
if (preparedStatement != null) preparedStatement.close();
if (rs != null) rs.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
return null;
}

Your problem is that you prepare the statement with
preparedStatement = dbConnection.prepareStatement(selectSQL);
which is correct, but then when you try to execute the PreparedStatement you supply the selectSQL string again:
rs = preparedStatement.executeQuery(selectSQL);
That is incorrect. You've already prepared the statement, so when the time comes to execute it you just do
rs = preparedStatement.executeQuery();

Related

How do I pass data values from a particular column or field in a database into a variable in java?

Is there a way to pass data values for a MySQL database into a variable in Java?
This is what I have tried so far:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login", "root", "****");
String query = "Select username, passphrase from student where username=?";
statement = connection.prepareStatement(query);
resultSet = statement.executeQuery(query);
if (resultSet.next()) {
_name = resultSet.getString(2);
_pass_phrase = resultSet.getString(3);
}
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
assert resultSet != null;
resultSet.close();
statement.close();
}
but I keep on getting a NullPointerException that points to my _name variable, telling me it empty. Could someone please point out to me what it is doing, and how to correct it?

Hive 2 JDBC PreparedStatement throws an error cannot recognize input near '?' '<EOF>' '<EOF>' in expression specification

try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
String query = "SELECT spd_field_label_id FROM RAL WHERE SUBJECT_USER_ID = ?";
PreparedStatement stmt = null;
Connection con = null;
boolean testCasePassed = false;
try {
con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
stmt = con.prepareStatement(query);
stmt.setString(1, "USR-44");
ResultSet resultSet = stmt.executeQuery(query);
Assert.assertNotNull(resultSet);
while (resultSet.next()) {
testCasePassed = true;
System.out.println("=======Test =========" + resultSet.getString("spd_field_label_id"));
}
} finally {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
}
return testCasePassed;
RAL is a simple Hive table with String type columns spd_field_label_id and SUBJECT_USER_ID.
Simple PreparedStatement using Hive2 throwing an Error stacktrace below. Any pointers on what could be wrong? Same query works fine when using Statement instead of PreparedStatement and without using ? for parameter binding.
org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 1:62 cannot recognize input near '?' '<EOF>' '<EOF>' in expression specification
at org.apache.hive.jdbc.Utils.verifySuccess(Utils.java:264)
at org.apache.hive.jdbc.Utils.verifySuccessWithInfo(Utils.java:250)
at org.apache.hive.jdbc.HiveStatement.runAsyncOnServer(HiveStatement.java:309)
at org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:250)
at org.apache.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:434)
stmt.executeQuery(query);
You're using the wrong method. You've already prepared the statement. It is ready to execute. It should be:
stmt.execute();

How can I retrieve the maximum value of a MySQL primary key in JDBC?

I'm working on this code but it ain't working. I've put another query which is working but not this one. Help will be much appreciated.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) FROM complaints");
if(rs != null)
{
while(rs.next())
{
String cno=rs.getString("C_NO");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}
In your query
SELECT MAX(PHONE) FROM complaints
you are not assigning an alias to the result. These functions usually return random or default column names, so when you perform
String cno=rs.getString("C_NO");
the C_NO column does not exist on the result set.
To fix it, fix your query like this
SELECT MAX(PHONE) as C_NO FROM complaints
With as C_NO I am giving this column the alias name you are trying to get.
Your select part of the query does not have C_NO , If you need max phone then your query will be:
SELECT MAX(PHONE) as max_phone FROM complaints
assuming that phone is long your complete code will be :
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) as max_phone FROM complaints");
if(rs != null)
{
while(rs.next())
{
Long cno=rs.getLong("max_phone");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}

Error on running multiple select query apache derby

I am not able to run code below with multiple select query. I am able to run queries below individually but I want to run all together and store their results in ArrayList. Error I get is java.sql.SQLException: ResultSet not open. Operation 'next' not permitted. Verify that autocommit is off.
Any advice? or is there a better way to do this? Thanks
public ArrayList<String> getTotalCountBasicQueries() {
ArrayList<String> totalCount = new ArrayList();
Statement stmt = null;
stmt = conn.createStatement();
conn.setAutoCommit(false);
try {
String q1 = "select count query";
String q2 = "select count query2";
String q3 = "select count query3 ";
ResultSet rs = stmt.executeQuery(q1);
ResultSet rs2 = stmt.executeQuery(q2);
ResultSet rs3 = stmt.executeQuery(q3);
while (rs.next()) {
totalBasicCount.add(rs.getString(1));
}
while (rs2.next()) {
totalCount.add(rs2.getString(1));
}
while (rs3.next()) {
totalCount.add(rs3.getString(1));
}
rs.close();
rs2.close();
rs3.close();
stmt.close();
} catch (Throwable e) {
System.out.println("Table fetch failed or result data failed");
} finally {
if (stmt != null) {
try {
stmt.close();
System.out.println("Could not close query");
} catch (SQLException ex) {
System.out.println("Could not close query");
}
}
return totalBasicCount;
}
}
}
See the javadoc for ResultSet :
A ResultSet object is automatically closed when the Statement object
that generated it is closed, re-executed, or used to retrieve the next
result from a sequence of multiple results.
you can't have multiple resultset open for a unique statement, per spec. however, some jdbc driver allow this
try :
ResultSet rs = stmt.executeQuery(q1);
while (rs.next()) {
totalBasicCount.add(rs.getString(1));
}
ResultSet rs2 = stmt.executeQuery(q2);
while (rs2.next()) {
totalCount.add(rs2.getString(1));
}
ResultSet rs3 = stmt.executeQuery(q3);
while (rs3.next()) {
totalCount.add(rs3.getString(1));
}

could not fetch all data from database in resultset

i am fetching all data from database and stored the resultset to a list. but could not fetch all data. i want to store the data in a dropdownlist. My code is bellow.
public static void updateChallan(){
ChallanNumber pd=null;
int i=0;
String customerName="";
List<ChallanNumber> challanList= new ArrayList<ChallanNumber>();
Connection con = DB.getConnection();
try
{
String st="select CHALLAN_NUMBER,CUSTOMER_CODE,CHALLAN_DATE from DELIVERY_CHALLAN_DETAILS order by CHALLAN_NUMBER";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(st);
while(rs.next())
{
String stCustName="select CUSTOMER_NAME from CUSTOMER_DETAILS where CUSTOMER_CODE='"+rs.getString(2)+"'";
Statement stmtCustName=con.createStatement();
ResultSet rsCustName=stmtCustName.executeQuery(stCustName);
while(rsCustName.next()){
customerName=rsCustName.getString(1);
}
customerName=rsCustName.getString(1);
//System.out.println(customerName +" "+i);
pd=new ChallanNumber(rs.getString(1),customerName,rs.getString(3));
challanList.add(i,pd);
i++;
}
}
catch(Exception e)
{
//e.printStackTrace();
}
render(challanList);
}
Dropdownlish code is in bellow.
<select name="challanNumber" id="challanNumber">
<option value="selected" selected="selected">ChallanNumber-CustomerCode- Date</option>
#{list challanList, as:'cl'}
<option value="${cl.challanNumber}">${cl.challanNumber}(${cl.customercode}-${cl.challanDate})</option>
#{/list}
</select>
The problem is that you are not closing the Connection and ResultSet when you get an exception. And so the database has exhausted all open cursors.
You need to close everything you open, it means statement, resultsets. You do that in the finally part of your try/catch to ensure things are correctly closed.
When you close a statement, the resultset linked to that statement is closed too.
public static void updateChallan() throws Exception {
ChallanNumber pd = null;
int i=0;
String customerName = "";
List<ChallanNumber> challanList= new ArrayList<ChallanNumber>();
Connection con = DB.getConnection();
Statement stmt = null;
try {
String st = "select CHALLAN_NUMBER,CUSTOMER_CODE,CHALLAN_DATE from DELIVERY_CHALLAN_DETAILS order by CHALLAN_NUMBER";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(st);
while (rs.next()) {
String stCustName = "select CUSTOMER_NAME from CUSTOMER_DETAILS where CUSTOMER_CODE='" + rs.getString(2) + "'";
Statement stmtCustName = con.createStatement();
try {
ResultSet rsCustName = stmtCustName.executeQuery(stCustName);
while (rsCustName.next()){
customerName = rsCustName.getString(1);
}
} finally {
if (stmtCustName != null)
stmtCustName.close();
}
customerName = rsCustName.getString(1);
//System.out.println(customerName +" "+i);
pd = new ChallanNumber(rs.getString(1), customerName, rs.getString(3));
challanList.add(i, pd);
i++;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
}
render(challanList);
}
Besides, you should read the docs of PlayFramework (here for Play2) there are database stuff to avoid using ResultSets and Statements directly, dealing with higher structures like domain objects, the framework will do the rest for you.

Categories