i am having problem in updating database.It doesnt update any field i edit.Please help
I have the code as below
package model;
import java.sql.*;
public class Datahandler {
public ResultSet databaseResult(Connection c,String query) throws SQLException{
Statement stmt=c.createStatement();
ResultSet rs=stmt.executeQuery(query);
return rs;
}
public void databaseDelete(Connection c,String query) throws SQLException{
Statement stmt=c.createStatement();
stmt.executeUpdate(query);
}
public int databaseInsert(Connection c,Contactdb pb) throws SQLException{
int rowsaffected=0;
try{
String query="INSERT INTO contactDb (first_name,last_name,phone_number,company_name,state,city,street,building_no) VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement statement = c.prepareStatement(query);
statement.setString(1, pb.get_firstname());
statement.setString(2,pb.get_lastname());
statement.setString(3, pb.get_phonenumber());
statement.setString(4, pb.get_companyname());
statement.setString(5, pb.get_state());
statement.setString(6, pb.get_city());
statement.setString(7, pb.get_street());
statement.setInt(8,pb.get_buildingno());
statement.execute();
} catch(SQLException e){
e.printStackTrace();
} finally {
c.close();
}
return rowsaffected;
}
public int databaseUpdate(Connection c,Contactdb pb) throws SQLException{
int a=0;
try{
String query="UPDATE contactDb SET first_name=?,last_name=?,phone_number=?,company_name=?,state=?,city=?,street=?,building_no=? WHERE sn=?";
a=69;
PreparedStatement statement = c.prepareStatement(query);
statement.setString(1, pb.get_firstname());
statement.setString(2,pb.get_lastname());
statement.setString(3, pb.get_phonenumber());
statement.setString(4, pb.get_companyname());
statement.setString(5, pb.get_state());
statement.setString(6, pb.get_city());
statement.setString(7, pb.get_street());
statement.setInt(8,pb.get_buildingno());
statement.setInt(9,pb.get_sn());
} catch(SQLException e){
e.printStackTrace();
} finally{
c.close();
}
return a;
}
}
i am having problem in updating database.It doesnt update any field i edit.Please help
The method databaseUpdate() seems to be missing statement.executeUpdate() which will execute the update statement.
You forgot to execute the database update statement after setting all the fields of the table.
public int databaseUpdate(Connection c,Contactdb pb) throws SQLException{
int a=0;
try{
String query="UPDATE contactDb SET first_name=?,last_name=?,phone_number=?,company_name=?,state=?,city=?,street=?,building_no=? WHERE sn=?";
a=69;
PreparedStatement statement = c.prepareStatement(query);
statement.setString(1, pb.get_firstname());
statement.setString(2,pb.get_lastname());
statement.setString(3, pb.get_phonenumber());
statement.setString(4, pb.get_companyname());
statement.setString(5, pb.get_state());
statement.setString(6, pb.get_city());
statement.setString(7, pb.get_street());
statement.setInt(8,pb.get_buildingno());
statement.setInt(9,pb.get_sn());
*statement.executeUpdate();*
}
catch(SQLException e){
e.printStackTrace();
}
finally{
c.close();
}
return a;
}
}
Related
So i hava an oracle functiion like: function unbind (ids in id_table). It takes an array of ids to perform some updates on my database.
The question is how can I run my function in order to perform update operations?
What I've alreade tried:
1. Query query = getSession().createSQLQuery("call UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
but I got ora-06576 not a valid function or procedure name
Query query = getSession().createSQLQuery("execute UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
finish with ora-00900 invalid sql statement
Long [] myArray = movedIds.toArray(new Long[movedIds.size()]);
Boolean result = getSession().doReturningWork(new ReturningWork<Boolean>() {
#Override
public Boolean execute(Connection connection) throws SQLException {
CallableStatement callableStatement = connection.prepareCall("{ ? = call UNBIND(:ids)");
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.setArray(2, connection.createArrayOf("id_table", myArray));
callableStatement.execute();
return !(callableStatement.getInt(1) == 0);
}
});
finishes with java.sql.sqlfeaturenotsupportedexception unsupported feature
The app conects to the database via jboss, so I suppose that could be the problem in p. 3?
SELECT
UNBIND( id_table (6271789) ) FROM DUAL
does not work because my function performs updates...
Anyway is there any other method to run a function that takes an array as a parameter directly from java code?
here is a simple example, does this help?
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#//localhost/orcl","scott","tiger");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "{ ? = call test_func(?) }";
CallableStatement cs = null;
try {
cs = conn.prepareCall(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int inVal = 0;
cs.setInt(2, inVal);
cs.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER);
cs.executeUpdate();
int res = cs.getInt(1);
System.out.println("result is " + res);
}
}
#Override
public byte[] findByusernameAndtenantId(String username,int tenantId) throws SQLException {
Connection con=null;
Blob img ;
byte[] imgData = null ;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con=DriverManager.getConnection("jdbc:cassandra://169.46.155.77:9042/demo");
String query = "SELECT PHOTO FROM demo.IGNITE_USERS where USER_NAME=? and TENANT_ID=?";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next ())
{
img = result.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
result.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try{
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
return imgData ;
}
this is my implementation code .
#RequestMapping(value ="/Image",method = RequestMethod.POST, produces="image/jpg")
public ResponseEntity<byte[]> getImage(#RequestParam String username,#RequestParam int tenantId) throws SQLException
{
byte[] img=null;
img=authService.findByusernameAndtenantId(username,tenantId);
System.out.println("testing functionality");
return new ResponseEntity<byte[]>(img, HttpStatus.OK);
}
this is my controller code
when I run the spring boot program , and do a POST call in Postman client to get the image I am getting Class not found exception : org.apache.cassandra.cql.jdbc.Cassandra Driver.
Can you please help me how to return that image from cassandra DB stored as Blob ?
I need to compute the number of rows in a hive table, for that
I am using the query:
ANALYZE TABLE p_7 COMPUTE STATISTICS noscan
I want to fetch the results through java, I am trying with the below
code and have no luck. the error I get is :
Exception in thread "main" java.sql.SQLException: The query did not generate a result set!
at org.apache.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:393)
at HiveJdbcClient.main(HiveJdbcClient.java:22)
code I am using is :
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveJdbcClient {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "hive", "");
System.out.println("connected");
Statement statement = con.createStatement();
String query = "ANALYZE TABLE p_7 COMPUTE STATISTICS noscan";
ResultSet res = statement.executeQuery(query);
}
}
I dont know how to execute a query such as:
ANALYZE TABLE p_7 COMPUTE STATISTICS noscan
through java. Any help on this would be of great help to me. Thanks.
Use the ANALYZE TABLE statement without 'NOSCAN' to compute the number of rows.
Note: This statement does not produce resultSet object.
To fetch the stored stats, use the following statement.
DESCRIBE FORMATTED tableName
In the output, the number of rows is listed in parameters array. Use regex to extract it.
Here is the sample code:
String analyzeQuery = "ANALYZE TABLE p_7 COMPUTE STATISTICS";
String describeQuery = "DESCRIBE FORMATTED p_7";
stmt.execute(analyzeQuery);
StringBuilder sb = new StringBuilder();
try (ResultSet rs = stmt.executeQuery(describeQuery)) {
while (rs.next()) {
int count = rs.getMetaData().getColumnCount();
for (int j = 1; j <= count; j++) {
sb.append(rs.getString(j));
}
}
}
System.out.println("Output: "+ sb.toString());
Refer https://cwiki.apache.org/confluence/display/Hive/StatsDev for details on Table and Partition statistics.
Try the below code for getting number of rows of a table:
public static Connection createConnection(String hive_ip)
{
String hive_url="jdbc:hive2://"+hive_ip;
Connection con=null;
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
System.out.println(hive_url+"/");
con = DriverManager.getConnection(
hive_url+"/",
hive_username,hive_password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static int getHiveColumnRowCount(String tablename,String db_name)
{
int count=0;
Connection con=createConnection();
try {
Statement st=con.createStatement();
int i=0;
String count_query="show tblproperties "+db_name+"."+tablename;
ResultSet rs=st.executeQuery(count_query);
while(rs.next())
{
i++;
if(i==3)
{
count=Integer.parseInt(rs.getString(2));
}
}
System.out.println("COUNT:"+count);
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
Hope it helps :)
I have JDBC Dao Object, and used PreparedStatements to do UPDATE a row at a table in my DB.
I have other methods such as SELECT and INSERT which are successful (insert-commit works).
But the update, just does not commit the changes (does not work at all). While the same UPDATE statement works from Oracle SQLServer directly.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StaffDAO {
private Connection conn;
public StaffDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Oracle Driver not found");
System.exit(0);
}
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#db01.xxxdev.com:1521:training",
"training", "training");
} catch (SQLException e) {
System.out.println("Driver manager failed");
}
}
public ResultSet getAllResultSet() {
String sql = "select * from ben_staff";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
return rs;
}
public Staff viewEmployee(String id) throws Exception {
Staff st = new Staff();
String sql = "SELECT * from BEN_STAFF where BEN_STAFF.id =\'" + id
+ "\'";
// String psql = "SELECT * FROM BEN_STAFF WHERE ID = ?";
Statement statement = null;
// PreparedStatement pstatement = null;
try {
statement = conn.createStatement();
// pstatement = conn.prepareStatement(psql);
// pstatement.setString(1, id);
} catch (SQLException e) {
System.out.println("Create Statement failed");
System.exit(1);
}
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
// rs = pstatement.executeQuery();
while (rs.next()) {
st.setId(rs.getString("ID"));
st.setLastName(rs.getString("LASTNAME"));
st.setFirstName(rs.getString("FIRSTNAME"));
st.setMi(rs.getString("MI"));
st.setAddress(rs.getString("ADDRESS"));
st.setCity(rs.getString("CITY"));
st.setState(rs.getString("STATE"));
st.setTelephone(rs.getString("TELEPHONE"));
st.setEmail(rs.getString("EMAIL"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return st;
}
public boolean insert(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "insert into ben_staff (id, lastname, firstname, mi, address, city, state, telephone, email)"
+ "values (?,?,?,?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(psql);
// pstmt.setString(1,st.getId());
// pstmt.setString(2, st.getLastName());
// pstmt.setString(3, st.getFirstName());
pstmt.setString(1, id);
pstmt.setString(2, last);
pstmt.setString(3, first);
pstmt.setString(4, mi);
pstmt.setString(5, address);
pstmt.setString(6, city);
pstmt.setString(7, state);
pstmt.setString(8, telephone);
pstmt.setString(9, email);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public boolean update(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "update ben_staff set lastname=?, firstname=?, mi=?, address=?, city=?, state=?,"
+ " telephone=?, email=? where id=?";
try {
pstmt = conn.prepareStatement(psql);
pstmt.setString(1, last);
pstmt.setString(2, first);
pstmt.setString(3, mi);
pstmt.setString(4, address);
pstmt.setString(5, city);
pstmt.setString(6, state);
pstmt.setString(7, telephone);
pstmt.setString(8, email);
pstmt.setString(9, id);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try{
conn.rollback();
} catch (SQLException exx){
System.out.println("Update Rollback Failed");
}
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What does pstmt.executeUpdate(); return? That would tell you how many rows are being updated. Something like
int numRows = pstmt.executeUpdate();
System.out.println( "Update modified " + numRows + " rows." );
My guess is that your update isn't actually modifying any rows. That would imply that the id being passed in was incorrect. Remember that string comparisons in SQL Server are case insensitive by default while they are case sensitive by default in Oracle.
Well always teach me this way of open and close connections from database, then i search more and more because this is very important for the performance of my application.
Here is my Class connection
public class Connection {
jdbc:oracle:thin:#//xxx.xx.x.xxx:xxxx/xxxxx.xxxxxx.xxxxx.xxx;
protected static Connection cn = null;
protected Connection getCn() {
return cn;
}
public static void setCn(Connection cn) {
Connection.cn = cn;
}
public ResultSet select(String sql) throws Exception {
ResultSet rs = null;
Statement st = null;
try {
st = this.getCn().createStatement();
rs = st.executeQuery(sql);
} catch (java.sql.SQLException e) {
throw e;
}
return rs;
}
public void insert(String sql) throws Exception {
Statement st = null;
try {
st = this.getCn().createStatement();
st.executeUpdate(sql);
} catch (java.sql.SQLException e) {
throw e;
}
}
public Connection connect() throws Exception {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
setCn(DriverManager.getConnection(DBURL, "user", "password"));
} catch (java.sql.SQLException e) {
throw e;
}
return cn;
}
Well that was for my Connection Class, now here i have some others class that extends from my Connection class to bring me data from the DataBase.
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}
im using jsf and oracle, i think this snippet should be in my class Connection after the catch but generates me and error of the resulset is closed when i execute the method rs.next() and is logic because the statement must be close after the reading data of the resultSet, so how can i close the statement in my class Connection or in other place??? any suggestions? please help me
finally {
if (st != null) {
st.close();
}
}
A quick fix to the problem is:
finally {
try{ st.close(); }catch( Exception ex ) { /* do nothing*/ }
}
this prevents from throwing an error when something goes wrong with the statement in other places of the code ( st is null, st is closed etc.).
A more elegant solution might be creating a helper class with methods that close statements, resultsets etc. and hide exceptions that occur:
class DbCloser{
static void closeQuietly( Statement st ){
try{
st.close();
} catch( Exception ex ){
/* do nothing */
}
}
static void closeQuietly( ResultSet rs ){
try{
rs.close();
} catch( Exception ex ){
/* do nothing */
}
}
// .... etc.
}
and then use that helper class in finally blocks in code:
finally {
DbCloser.closeQuietly( st );
}
There is ready-made DbUtils package from Appache Commons that has already implemented such helper methods, just download this library and place it in the class-path, see this links for details:
http://commons.apache.org/proper/commons-dbutils/
http://commons.apache.org/proper/commons-dbutils/apidocs/index.html
And finally I would suggest to place close methods only in finnaly blocks:
try {
......
rs = this.select(sql);
.......
...........
// Do not close the statement here ......
// rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
// ..... always close it here !!!
DbUtils.closeQuietly( st );
.........
}
i use this one
finally {
try{
if(st!=null){
st.close();
st=null;
}
}catch( Exception ex )
{
/* you can log this*/
}
}
Finally, I solved it like this:
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close();
rs.getStatement().close(); 'This works for me =)
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}