I have written some code that retrieves a video from a database. This video is stored as a BLOB file. I have retrieved it in
package edu.jay.fyp.featureextractor.database;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleResultSet;
import oracle.ord.im.OrdVideo;
public class OracleConnector {
private static final String dbUrl = "jdbc:oracle:thin:#jay_tank-pc:1521:fyp";
private static final String user = "SYSTEM";
private static final String pwd = "xyz";
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
OracleConnection connection = (OracleConnection) DriverManager.getConnection(dbUrl,user,pwd);
System.out.println("Connected");
String query = "select video_name, video_content from system.videos where sr_no = '1'";
PreparedStatement ps = connection.prepareStatement(query);
OracleResultSet rs = (OracleResultSet) ps.executeQuery();
OrdVideo videoProxy = null;
if(rs.next()){
rs.getORAData("video_content", OrdVideo.getORADataFactory());
}
//System.out.println(videoProxy.getBitRate());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I used code similar to the code given in Oracle's documentation, but when I run my code, I get the following exceptions:
Exception in thread "main" java.lang.ClassCastException: oracle.sql.BLOB cannot be cast to oracle.sql.STRUCT
at oracle.ord.im.OrdVideo.create(OrdVideo.java:1797)
at oracle.ord.im.OrdVideo$1.create(OrdVideo.java:1786)
at oracle.jdbc.driver.Accessor.getORAData(Accessor.java:1387)
at oracle.jdbc.driver.OracleResultSetImpl.getORAData(OracleResultSetImpl.java:1408)
at oracle.jdbc.driver.OracleResultSet.getORAData(OracleResultSet.java:632)
at edu.jay.fyp.featureextractor.database.OracleConnector.main(OracleConnector.java:28)
Well, I don't know much about this but I've done some research.
The error, if you read it says that a blob cannot be cast to a struct. That gives you a hint that you're providing wrong arguments to the getORAData().
I went and looked at the definition, and it says:
Get the column value as an instance of a subclass of ORAData
Well, if you look at the ORAData definition it doesn't seem to support BLOB, but only more common value types.
So, clearly that is not the way to retrieve a BLOB from the DB.
Searching on how to actually do that, I found this Java: Reading Blob from Oracle
In the response you can see that he suggest using ResultSet.getBinaryStream()
So your code should probably be:
rs.getBinaryStream("video_content")
Or
rs.getBytes("video_content")
Of course now you have to pick up the InputStream or the byte[] results and do something with them, but I'll leave that for you.
Related
I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc
Using UCanAccess for the first time for a project and I am having a lot of trouble inserting a row into one of my database tables (in Microsoft Access).
My code makes sense but once I execute I end up getting the same error every time, even though NetBeans is able to connect to my database.
package Vegan;
import java.sql.Connection;
import java.sql.DriverManager;
public class connectionString {
static Connection connection = null;
public static Connection getConnection()
{
try
{
connection = DriverManager.getConnection("jdbc:ucanaccess://C://MyDatabase1.accdb");
System.out.println("---connection succesful---");
}
catch (Exception ex)
{
System.out.println("Connection Unsuccesful");
}
return connection;
}
package Vegan;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB {
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Connection connection = null;
public DB() {
connection = connectionString.getConnection();
}
public void AddTest() {
try {
String sql = "INSERT INTO CategoryTbl(CategoryName) VALUES (?)";
ps = connection.prepareStatement(sql);
ps.setString(1, "Flours");
ps.executeUpdate();
System.out.println("Inserted");
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage().toString());
}
}
After that, when I execute the the AddTest() method, I get this system output:
run:
---connection succesful---
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:724)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:297)
UCAExc:::3.0.6 null
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:234)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1375)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:1624)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:1462)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:161)
at net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:253)
at Vegan.DB.AddTest(DB.java:91)
at Vegan.TestDB.main(TestDB.java:17)
BUILD SUCCESSFUL (total time: 1 second)
With no changes being made to the database when I check on it again Access.
What could be causing this, and what does the error message mean? Thank you
"java.nio.channels.NonWritableChannelException" means that the database file cannot be updated. In your case that was because the database file was in the root folder of the Windows system drive (C:\) and mere mortals have restricted permissions on that folder.
Solution: Move the database file to a folder where you have full write access.
I'm trying to insert rows in SQLite embedded DB in java. after adding changes are visible in that program alone. I can't see the changes in sqlite manager. When I try to insert a row in sqlite manager values that inserted which are shown in the program gets deleted. And showing those row that I added using sqlite manager. Please help..
connection class
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class HsqlConn {
//public static void main(String[] args) {
public static Connection hconn = null;
public static Statement hstmt = null;
public static PreparedStatement pst = null;
public static void hConnectDb(){
try{
Class.forName("org.sqlite.JDBC");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("PS/PSDB.sqlite");
hconn = DriverManager.getConnection("jdbc:sqlite::resource:"+resource);
}
catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
main class using that db
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
hConnectDb();
String sql1 = "Insert into Bill (billNo,date,principal,principalText,custId,dueDate) values (?,?,?,?,?,?)";
pst = hconn.prepareStatement(sql1);
pst.setString(1,BillNoField.getText());
pst.setString(2,dateField1.getText());
pst.setString(3,PrincipalField.getText());
pst.setString(4,PrincipaTextField.getText());
pst.setString(5,custIdField.getText());
pst.setString(6,dueDateField.getText());
pst.executeUpdate();
pst.close();
hconn.close();
JOptionPane.showMessageDialog(null, "saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
According to the documentation of sqlite-jdbc, connection URL strings beginning with "jdbc:sqlite::resource:" are for loading read-only SQLite databases:
2009 May 19th: sqlite-jdbc-3.6.14.1 released.
This version supports "jdbc:sqlite::resource:" syntax to access read-only DB files contained in JAR archives, or external resources specified via URL, local files address etc. (see also the
You need to specify a file in the filesystem containing your SQLite database. On Windows, an example is:
Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");
and on UNIX-like systems, an example is:
Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");
I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/
I'm trying to connect my application to my database.
I does not give a error, its runs but it doesn't fetch the info.
I've tried run tnsping from the command line to see if the listener is on, and it says that it's ok.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.io.*;
import javax.swing.*;
public class Connector extends JFrame{
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
Connection conn = null;
//Statement stmt = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:dbserver", "scott","tiger");
}
catch(SQLException e)
{ JOptionPane.showMessageDialog(null,e.getMessage(), "Erro na COnexao!",JOptionPane.ERROR_MESSAGE);
}
catch(Exception e)
{ e.printStackTrace();
}
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM AnimalM");
System.out.println ("Nome Salario");
if (rset.next()){
System.out.println("Aloooo");
int cod = rset.getInt(1);
String nome = rset.getString(2);
String nome_es = rset.getString(3);
int id = rset.getInt(4);
System.out.println (cod+" "+nome+" "+nome_es+" "+id);
}
rset.close(); //Close ResultSet
stmt.close(); //Close Statement
conn.close(); //Close Connection
}
}
It run until this instruction:
System.out.println ("Nome Salario");
And then nothing else shows, the program stops.
Does anyone have an idea of what might be happening?
I'd recommend stepping through with the debugger in Eclipse to see what's happening. Maybe the query returns no rows.
One design note: This class mixes UI, connection acquisition, and database access into one. A better approach would be do separate these into different classes. Test one feature, put it aside, and let the other classes simply use the functionality that you just implemented and proved to be working fine.
When you have one class doing too much you have no idea where the issue is when things go wrong.
You aren't closing your resources properly, either. Those should be wrapped in individual try/catch blocks.
I'd put all the code into one try/catch finally block and close the resources at the end.
I'd pass the connection into a data access object that would be responsible for acquiring the ResultSet and mapping it into objects or data structures.
I would move all Swing out of the database layer. You can reuse it without Swing that way (e.g. if you switch to a web UI).