How to store the fetched MySQL data into Optaplanner-examples - java

I have created a MySQL database with entries similar to nurse roster, i have generated these entries to be in XML format using below code.
package com.jdbcxml;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
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 org.w3c.dom.Document;
class EmployeeDAO
{
private Connection conn = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public EmployeeDAO()
{
String url = "jdbc:mysql://50.62.23.184:3306/dbname";
String userId = "root";
String passWord = "";
try
{
conn = DriverManager.getConnection(url, userId, passWord);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void finalize()
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Document getCustomerList()
{
Document doc = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
doc = JDBCUtil.toDocument(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return doc;
}
public String getCustomerListAsString()
{
String xml = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
xml = JDBCUtil.toXML(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return xml;
}
public static void main(String argv[]) throws Exception
{
EmployeeDAO dao = new EmployeeDAO();
String xml = dao.getCustomerListAsString();
System.out.println(xml);
Document doc = dao.getCustomerList();
System.out.println(doc);
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//out.write(doc);;
//out.close();
}
}
Now i need this data to be saved in Optaplanner-examples-->data-->nurserostering-->unsolved folder.
Also after doing this will the optaplanner be able to write a solution to the passed data to some file so that i can display those results on my webpage.

Why you storing the data you get from database to xml file? It will be more efficiently feed the data to optaplanner solver and get the best solution. Read my answer from your previous question HERE

Related

Corrupted docx file getting created while reading data from blob

I am trying to read the binary data and create a file with extension also given by user, code is working fine for pdf but for docx file, files are getting created but I am not able to open it as files are being created as corrupted.
Please find below the required details -
Table Schema
CWSMAin.java -
package org.cws;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class CWSMain {
private static DriverManagerDataSource dataSource;
private static BlobDAO blobDAO;
public static void main(String[] args) {
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/application");
dataSource.setUsername("root");
dataSource.setPassword("admin");
blobDAO = new BlobDAO(dataSource);
//int result = blobDAO.writeData("Resume_Anmol.pdf", "MyReume_Anmol.pdf");
blobDAO.readData(3);
}
}
BlobDAO.java -
package infy.cws;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mysql.jdbc.Blob;
public class BlobDAO {
private JdbcTemplate jdbcTemplate;
public BlobDAO(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int writeData(String inputFile, String outputFile) {
String sql = "INSERT INTO CWSPOC (bdata, file_name) VALUES (?,?)";
File file = new File("C:\\" + inputFile);
try {
FileInputStream input = new FileInputStream(file);
return jdbcTemplate.update(sql, input, outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return 0;
}
public boolean readData(int id) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/application", "root",
"admin");
String sql = "SELECT * FROM CWSPOC WHERE id=?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String fName = rs.getString("file_name");
System.out.println("File Name is " + fName);
File file = new File("E:\\" + fName);
FileOutputStream output = new FileOutputStream(file);
InputStream input = rs.getBinaryStream("bdata");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
Please let me know the solution, thanks in advance!
Note - Need to create file with proper extension as inputs given by user.

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

Download BLOB data from MySQL database via Java

I've a little problem; when I trying to download data (picture,audio...) from Mysql database.I'm getting damaged file so the file size is 1kb.I've changed file extension just in case but always got same results.
Please can anyone help me?
I've tried with this code :
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DownloadFileFromDb {
public static void main(String[] args) {
final String host = "jdbc:mysql://localhost/onurDB";
final String user = "onur";
final String pass = "onurdb958";
String SQL = "SELECT FILENAME FROM `PIC_STORE` WHERE `ID`=?";
Connection conn = null;
java.sql.PreparedStatement smt = null;
InputStream input = null;
FileOutputStream output = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting...");
conn = DriverManager.getConnection(host, user, pass);
System.out.println("Connection successful..\nNow creating query...");
smt = conn.prepareStatement(SQL);
smt.setString(1, "4"); //in this row we have a png picture
rs = smt.executeQuery();
output = new FileOutputStream(new File("/Users/MacbookPro/Downloads/pic.png"));
System.out.println("Getting file please be patient..");
while (rs.next()) {
input = rs.getBinaryStream("FILENAME"); //get it from col name
int r = 0;
/*
*there I've tried with array but nothing changed..Like this :
* byte[] buffer = new byte[2048];
* int r = 0;
* while((r = input.read(buffer)) != -1){
* out.write(buffer,0,r);}
*/
while ((r = input.read()) != -1) {
output.write(r);
}
}
System.out.println("File writing complete !");
} catch (ClassNotFoundException e) {
System.err.println("Class not found!");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("Connection failed!");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.err.println("File not found!");
e.printStackTrace();
} catch (IOException e) {
System.err.println("File writing error..!");
e.printStackTrace();
}finally {
if(rs != null){
try {
input.close();
output.flush();
output.close();
smt.close();
conn.close();
} catch (SQLException e) {
System.err.println("Connot close connecton!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
there is downloaded file : pic.png file size is 12 byte.
THANKS FOR ALL.
Solved :
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DownloadFileFromDb {
public static void main(String[] args) {
final String host = "jdbc:mysql://localhost/onurDB";
final String user = "onur";
final String pass = "onurdb958";
String SQL = "SELECT PICTURE FROM `PIC_STORE` WHERE `ID`=?"; //Here I mistakenly wrote 'FILANAME' here instead of a 'PICTURE'
Connection conn = null;
java.sql.PreparedStatement smt = null;
InputStream input = null;
FileOutputStream output = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting...");
conn = DriverManager.getConnection(host, user, pass);
System.out.println("Connection successful..\nNow creating query...");
smt = conn.prepareStatement(SQL);
smt.setString(1, "4"); //in this row we have a png picture
rs = smt.executeQuery();
output = new FileOutputStream(new File("/Users/MacbookPro/Downloads/pic.png"));
System.out.println("Getting file please be patient..");
while (rs.next()) {
input = rs.getBinaryStream("FILENAME"); //get it from col name
int r = 0;
while ((r = input.read()) != -1) {
output.write(r);
}
}
System.out.println("File writing complete !");
} catch (ClassNotFoundException e) {
System.err.println("Class not found!");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("Connection failed!");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.err.println("File not found!");
e.printStackTrace();
} catch (IOException e) {
System.err.println("File writing error..!");
e.printStackTrace();
}finally {
if(rs != null){
try {
input.close();
output.flush();
output.close();
smt.close();
conn.close();
} catch (SQLException e) {
System.err.println("Connot close connecton!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

How to return result set from method in jdbc connection

This is my connetion class. i need to return resultset to specific class. but i found resultset is closed in that class. i use connectio pooling in my connection.
i want to create general connection class that manages all operations for database in my application.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class OpenTestConnection {
private DataSource dataSource=null;
private Connection connection=null;
private Statement statement=null;
public OpenTestConnection()
{
System.out.println("come in Openconnection....");
try {
// Get DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/ietddb");
} catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public ResultSet selectfromtable(String sql)
{
System.out.println("come here....");
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
try { if(null!=resultSet)resultSet.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=statement)statement.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=connection)connection.close();} catch (SQLException e)
{e.printStackTrace();}
}
return resultSet;
}
}
Well Shree has answered your issue. You have closed the ResultSet before returning it.
However, to add to what you are trying to achieve.
1) surround your return dataSource.getConnection in try catch.
2) Create seperate query function and connection close function like below
protected Connection connection = null;
protected Statement statement = null;
protected PreparedStatement prepared = null;
// executeQuery
protected ResultSet execute(String sql) throws SQLException {
connection = getConnection();
statement = connection.createStatement();
return statement.executeQuery(sql);
}
//now have a close function
protected void commitAndClose() {
if (connection != null) {
try {
connection.commit();
} catch (SQLException ex) {
// your code for handling ex
} finally {
try {
resultSet.close(); //do not know why you are closing resultset
statement.close();
connection.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
connection = null;
}
}
}
This will give you more flexibilty when your code expands.

Connection Timeout while running sql procedure from servlet

I want to run a procedure which takes approx 15 minutes to run in sql environment. Whereas when I am trying to run it using Servlet I am getting Network error(TCP error). I am using Http Server using ajp to transfer request to Tomcat server. This is my code. can anybody tell me what is going wrong here.
import com.itech.softensity.utils.Utils;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class JdbcServlet extends HttpServlet
{
protected static Logger logger = Logger.getLogger(JdbcServlet.class);
static final String jtdsurl = "jdbc:jtds:sqlserver://<server_name>;instance=<instance>;DatabaseName=<databasename>;socketTimeout=100000;socketKeepAlive=true";
static final String USER = "username";
static final String PASS = "password";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection con = null;
CallableStatement stmt = null;
ResultSet result =null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
logger.info("Connecting to database...");
con = DriverManager.getConnection(jtdsurl, "username","password");
logger.info("Creating statement...");
String sql = "exec populateMobRefLit";
stmt = con.prepareCall(sql);
stmt.setQueryTimeout(100000);
stmt.executeQuery();
logger.info("Executing stored procedure check new...");
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
logger.info("Procedure run successfully values: ");
}
catch (Exception e) {
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
logger.info(Utils.stackTraceToString(e));
}
finally{
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have tried it with JTDS driver as well as microsoft provided jdbc driver as the drivers have specific timeouts. I have tried Hibernate, I have tried Spring, but nothing works.

Categories