Duplicate Entries by insert Derby DataBase Embedded - derby

I try to insert new Row in the DataDabe Derby and the new Data will be inserted but also Duplicate all the actual Data. Someone could tell me where i am making the big Mistake.
If some body could edit the code it would be so helpfull. I am trying to make a project for the school.
Thank you so much advanced.
#Override
public void addNewParkingReservation(ParkingReservation parkingReservation, UserAHB userAHB) throws DaoException {
this.userAHB = userAHB;
this.parkingReservation = parkingReservation;
String url = "jdbc:derby:" + urlDB;
this.daoFactory = new DaoFactory(url);
this.connection = daoFactory.connect();
if(connection!=null) {
String sql = "INSERT into parking(idparking, buchungsname, autokfz, anreisedatum, abreisedatum, anzahltagen, betragparking, "
+ "buchungskanal, bemerkungen, schluesselinhaus, verkaufer) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = null;
try {
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, parkingReservation.getIdParking());
preparedStatement.setString(2, parkingReservation.getBuchungsname());
preparedStatement.setString(3, parkingReservation.getAutoKFZ());
preparedStatement.setDate(4, parkingReservation.getAnreiseDatum());
preparedStatement.setDate(5, parkingReservation.getAbreiseDatum());
preparedStatement.setInt(6, parkingReservation.getAnzahlTagen());
preparedStatement.setDouble(7, parkingReservation.getBetragParking());
preparedStatement.setString(8, parkingReservation.getBuchungsKanal());
preparedStatement.setString(9, parkingReservation.getBemerkungen());
preparedStatement.setString(10, parkingReservation.getSchluesselInHaus());
preparedStatement.setString(11, parkingReservation.getAbkuerzungMA());
preparedStatement.executeUpdate();
this.connection.commit();
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
this.connection.close();
this.daoFactory.shutdown();
// displayListParking();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Connection connect() {
JOptionPane.showMessageDialog(null, "DaoFactory Hora de crear conexion: " + DaoFactory.url);
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
//Get a connection
try {
connection = DriverManager.getConnection(DaoFactory.url);
// connection.setAutoCommit(false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}

Related

call an oracle function with array as parameter via hibernate

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);
}
}

how to convert blob data into byte array and get image from DB and send it to UI through rest api

#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 get a nullpointerexception when connecting to oracle DataBase

Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.

JDBC Update on Oracle failed to commit

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.

Posting HTTPS form results in html 404 status code

I keep getting a HTML 404 reply from the server when I try to login via a httppost (https). Not sure if this is a cookie problem or something else. The code should be good as I have copied it from another activity. I need some help.
This is my current code:
public int postData(String usernamne, String password) {
String url = "https://domainname.com/nclogin.submit";
HttpPost httppost = new HttpPost(url);
try {
KeyStore trusted = null;
try {
trusted = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
trusted.load(null, "".toCharArray());
MySSLSocketFactory sslf = null;
try {
sslf = new MySSLSocketFactory(trusted);
} catch (KeyManagementException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
}
sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("f_username", "myemail#address.com"));
nameValuePairs.add(new BasicNameValuePair("f_passwd", "mypassword"));
nameValuePairs.add(new BasicNameValuePair("f_method", "LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", sslf, 443));
SingleClientConnManager cm = new SingleClientConnManager(httppost.getParams(), schemeRegistry);
// NEW API WONT ALLOW THIS IN THE MAIN THREAD! hence ASYNC
DefaultHttpClient client = new DefaultHttpClient(cm, httppost.getParams());
HttpResponse result = client.execute(httppost);
// Check if server response is valid
StatusLine status = result.getStatusLine();
Log.d(TAG, "STatus" + result.getStatusLine());
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
HttpEntity entity = result.getEntity();
InputStream is = entity.getContent();
if (is != null) {
is.close(); // release connection
}
String phpsessid = "";
// cookies from another blog
// http://stackoverflow.com/questions/4224913/android-session-management
List cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d(TAG, "no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
// Log.d(TAG, "COOKIE-" + i + " " +
// cookies.get(i).toString());
if (cookies.get(i).toString().contains("PHPSESSID")) {
phpsessid = cookies.get(i).toString();
Log.d(TAG, "COOKIE FOR PHPSESSID - " + phpsessid);
}
}
} // end of blog
entity.consumeContent();
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return 1;
} // end of postData()
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
I know the url is correct, as are the name value pairs, as I can login via a query string via a browser or via wget:
https://domainname.com/nclogin.submit?f_username=myemail#email.com&f_passwd=password&f_method=LOGIN
This results in a connection established and a redirect to my dashboard page.
The HTML code (source) from the login page can be viewed
here

Resources