I wrote this query but it has a error.
String x = String.valueOf(jTable1.getModel().getValueAt(row, 2) );
try {
PreparedStatement preparedStatement1 = connection.prepareStatement("select sportman_code, "
+ "customer_code from sportman where sportman_code = ?");
preparedStatement1.setString(1, x);
preparedStatement1.executeUpdate();
} catch (Exception e) {
System.out.print(e.getMessage());
}
this is it's error
Can not issue executeUpdate() for SELECTs
what is problem?
Try
ResultSet resultSet = preparedStatement1.executeQuery();
instead of
preparedStatement1.executeUpdate();
resultSet = preparedStatement.executeQuery();
For issuing SQL SELECT's you have to use executeQuery and not executeUpdate. Also i see a ; hanging out there.
Related
public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}
I am new to using java with a database and I have been trying following code:
public int getDateDiff(int OrderID) {
Connection conn = DBConnection.getConnection();
Integer diff = null;
String getdiffSQL = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ?;";
try {
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(getdiffSQL);
while (rs.next()) {
diff = rs.getInt(1);
}
}
catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
return diff;
}
I tried running this but i encounter this
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"
and the the return diff is null. Please tell me what wrong in this and how do i fix this.
PreparedStatement#executeQuery() does not take a parameter and you should not be passing the query string. Instead use this pattern:
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(); // no parameter
This is a fairly common mistake made when using JDBC, partly because Statement#executeQuery() does take the query string as a parameter. Add to this tutorials like MkYong which make the same mistake as the OP and it is easy to see why this error is so prevalant.
I have problem with my SQL request, when I run my request, I receive this message error:
org.postgresql.util.PSQLException: A result was returned when none was expected.
Here is my request:
Connexion con = new Connexion();
try {
c = con.Connect();
stmt = c.createStatement();
int sqlCalcul = stmt.executeUpdate(
"SELECT inventaire FROM calcul WHERE designation='" + designation +
"' AND date=(SELECT MAX(date) FROM calcul)");
stmt.close();
// c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
You should use executeQuery instead of executeUpdate:
ResultSet sqlCalcul = stmt.executeQuery("SELECT inventaire...")
executeUpdate is used for a INSERT, UPDATE, or DELETE statement, and will throw an exception if a ResultSet is returned. executeQuery should be used for SELECT statements.
Take a look at PostgreSQL's tutorial using the JDBC driver for more information.
In my database bean I have a section of code which is below :
public Integer getTotalOrgPoints() {
try {
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
totalOrgPoints = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return totalOrgPoints;
}
For the statement QUERY_TOTAL_ORG_SCORE if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = 1
It will return the value for that organisation but if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = ?
I get nothing does anyone know why this is happening for me?.
Add this line to bind values for prepared statement before executequery
stmt.setInt(1, 1);
Modified:-
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
In the below code I want to call one stored procedures and execute one Query. I am facing error at statement.executeUpdate(); Please help in fixing it. I am not sure where it going wrong.
public void Dbexe() {
Connection connection;
connection = DatabaseConnection.getCon();
CallableStatement stmt;
try {
stmt = connection.prepareCall("{CALL optg.Ld_SOpp}");
stmt.executeUpdate();
stmt.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Stored Procedure executed");
//PreparedStatement statement = null;
// ResultSet rs = null;
try{
PreparedStatement statement;
try {
statement = connection.prepareStatement("MERGE INTO OPTG.R_VAL AS TARGET USING" +
........... +
"");
statement.executeUpdate(); //Here the exception is thrown
statement.close();
connection.commit();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// statement = connection.prepareStatement(query);
//statement.close();
}
finally{
System.out.println("Data is copied to the Table");
}
}
Little off-topic: You should use CallableStatement instead if you want to call a store procedure (see documentation):
CallableStatement callableStatement = connection.prepareCall("{call opptymgmt.Load_SiebelOpportunity}");
ResultSet rs = callableStatement.executeQuery();
I would also suggest you check this topic How to properly clean up JDBC resources in Java?. It was very helpful to me.
Update: based on this stack trace:
com.ibm.db2.jcc.am.mo: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=MERGE INTO OPPTYMGMT.REVENUE_VALIDAT;BEGIN-OF-STATEMENT;<variable_set>, DRIVER=4.7.85
The problem seems to be in the sql sentence you're trying to execute. I mean, is an error from DB2, not java. You should check your sql statement.
I got it working in this method:
PreparedStatement myStmt = conn.prepareStatement(sqlQuery);
myStmt.setInt(1, id); //position of parameter (1,2,3....) , value
ResultSet rs = myStmt.executeQuery();
while (rs.next()) {
int jobId = rs.getInt("jobId"); ....... }