Storing files to MySQL using jdbc code - java

I am unable to store image into MySQL database through the jdbc code below:
package com.jlcindia.jdbcfiles;
import java.sql.*;
import java.io.*;
public class Test1 {
public static void main(String []args){
Connection con=null;
PreparedStatement ps=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jlcstudents","root","garima");
ps=con.prepareStatement("insert into filetest (cno,file) values(1,?)");
File image=new File("C:\\html images\\MickeyMouse.jpg");
FileInputStream fis=new FileInputStream(image);
ps.setBinaryStream(2, fis);
ps.execute();
System.out.println("Record Inserted");
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if(ps!=null)
ps.close();
if(con!=null)
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
Error in console is as:
Exception in thread "main" java.lang.AbstractMethodError:
com.mysql.jdbc.PreparedStatement.setBinaryStream(ILjava/io/InputStream;)V
at com.jlcindia.jdbcfiles.Test1.main(Test1.java:19)

That error so far as I am aware means that the specific method hasn't been implemented, you can try however converting the file into a byte array and storing it using
ps.setBytes(<Byte Array>)
instead if the column is set to storing BLOB data

Related

How to read the SQL query from Excel and pass into JDBC code

Can someone suggest/help on the below query.
I have the below code which retrieve the data from database, the SQL query i am hard coding want to pass in excel and read the SQL query from excel and store the SQL query output in the result column.
package com.DBUtility;
import java.io.*;
import java.sql.*;
public class DataRetrieveMainClass {
public static void main(String args[]) throws Exception {
PrintColumnAndData PrintCl=new PrintColumnAndData();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#123.32.23.123:8080/orcl", "Test1", "******");
PreparedStatement ps = con.prepareStatement("select * from MSG where MID='1234'");
ResultSet rs = ps.executeQuery();
try {
PrintCl.printResultColumns(rs);
} catch (SQLException e) {
System.err.println(e.getMessage());
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
** - Excel File:**
SQL QUERY RESULT
______________________________________________________
select * from MSG where MID='1234'
public static void main(String args[]){
writeExcel(getSQLObjects());
}
private static ArrayList<MyObject> getSQLObjects(){
PrintColumnAndData PrintCl=new PrintColumnAndData();
ArrayList<MyObject> objList = new ArrayList<MyObject>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:#123.32.23.123:8080/orcl", "Test1", "******")){
PreparedStatement ps = con.prepareStatement("select * from MSG where MID='1234'");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
MyObject object = new MyObject();
//set object values for each column using rs.getString() etc.
objList.add(object);
}
}
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return objList;
}
private static void writeExcel(ArrayList<MyObject> objList) {
Workbook book = null;
try {
try {
book = new WorkbookFactory.create(new File("myFile"));
Sheet sheet = book.getSheet("mySheet");
int startRow = 1;
for(MyObject obj : objList) {
Row row = sheet.createRow(startRow);
row.getCell(0).setCellValue(obj.value);
row.getCell(1).setCellValue(obj.otherValue);
//etc.
startRow++;
}
book.write(new FileOutputStream(new File("myFile")));
}finally {
book.close();
}
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
That should be a huge help for you (might need to be modified slightly to fit your needs, but should give you a 'map' to your solution nonetheless). Your code seems a bit clumsy at the moment and very disorganized. You should separate your SQL database call and the excel writing into separate methods (if not classes) to handle these; I personally even create a class for the connection itself. You should also consider creating a class to represent an object to pass between the two (data transfer object).
Some things that I assumed: you are using Apache POI for excel, your excel file and the sheet for it already exist (you are just populating it), and you have headers in the first row of the sheet (hence startRow = 1).

JDBC.Ucanaccess shows SQLException message

i am new in database want to run first database program with Access but getting SQLException message "DB linking failed!"
i wrote following code with Java 8,and i have configured ucanaccess's libraries.
Java build path
<i>
import java.sql.*;
public class Db {
public static void main(String[] args)throws SQLException
{
Connection con =null;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dataSource = "jdbc:ucanaccess://D:/Database.accdb";
con=DriverManager.getConnection(dataSource,"","");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO Table1 (ID, Name) VALUES ('4','ann')");
st.execute("SELECT * FROM Table1");
ResultSet rs = st.getResultSet();
while(rs.next())
{
System.out.println(rs.getString("ID")+rs.getString("Name"));
}
st.close();
con.close();
}
catch(SQLException e)
{
System.out.println("DB linking failed!");
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
}
}
i have added "e.printStackTrace()" in the catch block as following
catch(SQLException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
and got following error messages
error messages

How to get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

Can't connect to sqlite from eclipse?

Hello guys so I have this simple java to do and I am trying to connect to an sqlite database from eclipse but it doesn't work at all.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private String pathDB="C:\\sqlite\\test.db";
private Connection connection=null;
private Statement statement=null;
public DatabaseConnection(String path){
pathDB= path;
}
public void connect () {
try {
Class.forName("org.sqlite.JDBC");
connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
statement= connection.createStatement();
System.out.println("Connection to " + pathDB + " "+ "successful");
} catch (ClassNotFoundException notFoundException) {
notFoundException.printStackTrace();
System.out.println("Connection Error!");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.out.println("Connection Error!");
}
String query="Insert into Identity values(0,'issam','issam#mail.com')";
try {
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the main class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnection connection= new DatabaseConnection("test.db");
connection.connect();
connection.close();
}
}
So I have this sqlite database but whenever I run the code it always gives me : Connection to "path" was successful, no matter what path I put...
I think I have done everything correctly, I downloaded the sqlite JDBC file and added it:
enter image description here
I tried adding a new row to a database table, but it always gives me this:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
at com.issam.iamcore.Main.main(Main.java:11)
Any help would be appreeciated, thanks !
You have successfully connected to the database, but did not create table Identity before executing insert query, as it says in the stack trace:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
Call this before inserting a row:
String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);

combination of Oracle database and in-memory database in java program

I am going to enhance the performance of my program. For this purpose I am going to implement some parts of my program to be done in memory instead of database. I dont know which one is better in this regards, in-memory database or normal java data structure.For in-memory database I considered Tentimes from oracle and H2. So another question would be which solution is better for around 100 million records of data on single machine for single user? Also another question would be is the old way of database connection works fine in this way? Here is the connection that I used for oracle, What is the appropriate Driver for this purpose.
public static Connection getConnection(){
//If instance has not been created yet, create it
if(DatabaseManager.connection == null){
initConnection();
}
return DatabaseManager.connection;
}
//Gets JDBC connection instance
private static void initConnection(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionUrl = "jdbc:oracle:thin:#localhost:1521:" + dbName;
DatabaseManager.connection =
DriverManager.getConnection(connectionUrl,"****","****");
}
catch (ClassNotFoundException e){
System.out.println("Oracle driver is not loaded!");
System.exit(0);
}
catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (Exception e){
}
}
public static ResultSet executeQuery(String SQL) throws SQLException
{
CachedRowSetImpl crs = new CachedRowSetImpl();
ResultSet rset = null ;
Statement st = null;
try {
st = DatabaseManager.getConnection().createStatement();
rset = st.executeQuery(SQL);
crs.populate(rset);
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}finally{
rset.close();
st.close();
}
return crs;
}
public static void executeUpdate(String SQL)
{
try {
Statement st = DatabaseManager.getConnection().createStatement();
st.executeUpdate(SQL);
// st.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
Regards.

Categories