Java/Groovy and MySQL: Checking if row exists in table - java

I am trying to check if a specific row exists in a table that includes two given parameters: record_id and modifiedDate. So far my code does not work.
public void doSomething(int RECORD_ID) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String modifiedDate = dateFormat.format(date);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Statement stmt = connection.createStatement();
String checkIfInDB = "select exists(select * from table where reference = ${RECORD_ID} and creation_date = '${modifiedDate}');"
ResultSet rs = stmt.executeQuery(checkIfInDB);
if(rs.next()) {
println "Query in db"
stmt.close();
connection.close();
return;
}
else {
String command = "INSERT INTO table(reference, creation_date) VALUES (${RECORD_ID}, '${modifiedDate}');"
stmt.executeUpdate(command)
println "Success"
stmt.close();
connection.close();
return;
}
}
If the user inserts a RECORD_ID and date that already exists, the program adds it to the table anyway, when it should print 'Query in db'.
I would appreciate any help to solve this issue.

Rather than listing what was wrong with the provided code I offer an example of a working example that could be used to help you along your journey...
public static void main(String[] args) {
int recordId = 1;
String jdbcSource = "jdbc:mysql://localhost:####/";
String user = "****";
String password = "****";
String checkIfInDB = "select count(*) as cnt from example_schema.example_table where example_table.reference = ? and example_table.creation_date = ?";
try (Connection connection = DriverManager.getConnection(jdbcSource, user, password)) {
PreparedStatement stmt = connection.prepareStatement(checkIfInDB);
stmt.setInt(1, recordId);
stmt.setDate(2, java.sql.Date.valueOf(LocalDate.now()));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("at least one row matched");
return;
} else {
// to-do implement insert statement
return;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

Related

How can I load a XML file to an XMLType column on Oracle 18c with java

I have a complex directory system with millions of xml files which i need to retrieve to an XMLType column in Oracle 18c. I'm working with a java method that is executed by a procedure to re-load this files on this particular table. Since a lot of the of the java libraries were deprecated i'm out of options to solve this issue. The way I had finded to workaround was a tempory table with a CLOB column where I can insert the content from the files and than inside oracle I insert those in the original table using a XMLType(clobVariable). BUT, it doesnt work on files larger then 20k characters.
If anyone can help me I'm more than glad to give more information.
(I'm from Brazil and maybe I didn't made myself clear on the explanation btw)
public static void inserirXml() throws Exception{
try {
int num_id_nfe;
String dirArquivo = "";
String query;
String queryUpdate;
String reCheck, insert;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
conn.setAutoCommit(false);
query = "SELECT ID_NFE, DSC_CAMINHO_XML FROM DFE_NFE_CAMINHO_XML WHERE FLG_CARREGADO = 0 AND ROWNUM <= 1000";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
stmt.executeQuery(query);
ResultSet rset = stmt.getResultSet();
while(rset.next() == true) {
try {
num_id_nfe = rset.getInt(1);
dirArquivo = rset.getString(2);
byte[] bytes = Files.readAllBytes(Paths.get(dirArquivo));
String xmlString = new String(bytes, "utf-8");
String insertQuery = "INSERT INTO DFE_NFE_REP_XML_TMP (ID_NFE, XMLCLOB) VALUES(?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
xmlString = xmlString.substring(1);
pstmt.setInt(1, num_id_nfe);
pstmt.setNString(2, xmlString);
pstmt.execute();
pstmt.close();
queryUpdate = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 1 WHERE ID_NFE = " + num_id_nfe + " \n";
stmt2.executeQuery(queryUpdate);
}catch(SQLException e) {
System.err.println(e.getMessage()+" loop");
stmt2.close();
throw e;
}
}
insert = "INSERT INTO DFE_NFE_REP_XML (ID_NFE, CONTEUDO) SELECT ID_NFE, XMLType(XMLCLOB) FROM DFE_NFE_REP_XML_TMP";
stmt4.executeUpdate(insert);
reCheck = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 0 WHERE id_nfe not in (select id_nfe from dfe_nfe_rep_xml) and flg_carregado = 1";
stmt3.executeQuery(reCheck);
conn.commit();
rset.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
conn.close();
} catch (SQLException x) {
System.err.println(x.getMessage()+" geral");
}catch (ClassNotFoundException y) {
throw y;
}catch(Exception z) {
throw z;
}
}

Truncated incorrect DOUBLE value using DELETE statement

int d1;
String attribute = comboBox1.getSelectedItem().toString(); // a combo box
System.out.println(attribute);
String data = t.getText(); // a textfield
System.out.println(data);
if (attribute.equals("COURSE_ID")) {
IsNumber in = new IsNumber();
d1 = in.stringToInt(data);
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "DELETE FROM course WHERE ? = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, attribute);
statement.setInt(2, d1);
boolean rows = statement.execute();
if (rows == true) {
new ViewDatabase(user, name, pswrd);
System.out.println("COURSE_ID UNIT UPDATE SUCCESSFUL!");
frame.setVisible(false);
} else if (rows == false) {
JOptionPane.showMessageDialog(null, "Cannot find row!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
For this piece of code, whenever I try to run it, it returns "Data truncation: Truncated incorrect DOUBLE value: 'COURSE_ID'". I'm not sure what this is referring to and I searched and found some people saying that this error message is misleading, though I only found answers to selects, inserts, and updates, but not deletes.
I also turned off strict mode in MySQL, as advised from the internet, but to no avail.
You can't bind strings to actual column names in a prepared statement. So, the attribute column names must be hard-coded. One pattern which might work would be:
String sql = "";
if ("COL1".equals(attribute)) {
sql = "DELETE FROM course WHERE COL1 = ?";
}
else if ("COL2".equals(attribute)) {
sql = "DELETE FROM course WHERE COL2 = ?";
}
else {
sql = "DELETE FROM course WHERE COL3 = ?";
}
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);
boolean rows = statement.execute();

Getting newly inserted id as empty string when I add SET NAMES to my insert statement

I have following program which insert emoji and any text to my MySql AWS Database. I was unable to add Emojis in my MySql database, but then i fixed this problem by changing collation and adding this-> SET NAMES utf8mb4; query before my previous insert query but now i am unable to get last inserted id from it. what should i do in order to insert emoji as well as to get last inserted id from it.
Here is my code.
public static JSONObject emoji(String comment) {
JSONObject json = new JSONObject();
Connection con = null;
PreparedStatement stmt = null;
String newInsertId = "";
try {
BasicDataSource bds = DBConnection.getInstance().getBds();
con = bds.getConnection();
String query = "SET NAMES utf8mb4; insert into emojis set message = '" + comment + "';";
stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
if (stmt.executeUpdate() > 0) {
json.put("success", 1);
}
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
newInsertId = rs.getString(1); //giving empty values cause of that SET NAMES utf8mb4; query
}
System.out.println(newInsertId); //empty
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
DbUtils.close(con);
DbUtils.close(stmt);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//参数2最好写上,虽然Mysql不写也能获取但是不代表别的数据库可以做到
ps.executeUpdate();
rs = ps.getGeneratedKeys();
int id = 0;
if (rs.next())
id = rs.getInt(1);
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
——————————————————————————————————————————————————————
Focus on this 'Statement.RETURN_GENERATED_KEYS'

how do i properly close cursor in loop body because i m getting ERROR: java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I have been encountered with ORA-01000 SQL exception since following code fetches more than thousand records, so in this regard i would like to know that how do i close ResultSet objects appropriately in loop body so that i may get rid of this exception. Please help me out ... it would b really appreciated ...
Note:-Even though I have opened 2000 cursors in Oracle database.
try
{
String usercode = session.get("usercode").toString();
Date dor = null;
Date eff_date =null;
String emp_category_code = "";
String emp_id = "";
String pay_com = "";
double new_da = 0;
double old_da =0;
int caseCount =0;
con = DBConnect.makeconnect();
con.setAutoCommit(false);
String div_name = session.get("division").toString();
PreparedStatement ps = con.prepareStatement("select emp_id ,category,pay_comm,da as old_da,nvl(pm.EMP_DOR,pm.EMP_DOD) as dor from ABC pm where pm.DIV_NM = ? and sent_to_trea= '1'");
ps.setString(1,div_name);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
emp_id = rs.getString("emp_id");
emp_category_code = rs.getString("category");
pay_com = rs.getString("pay_comm");
dor = rs.getDate("dor");
old_da = rs.getDouble("old_da");
ps = con.prepareStatement("select eff_date,per_amount from XYZ where cat_code=? and relief='DA' and eff_date=(select max(EFF_DATE) from XYZ where PAY_COM=? and cat_code=?) and pay_com=?");
ps.setString(1, emp_category_code);
ps.setString(2, pay_com);
ps.setString(3, emp_category_code);
ps.setString(4, pay_com);
ResultSet rst = ps.executeQuery();
if(rst.next())
{
eff_date = rst.getDate("eff_date");
new_da = rst.getDouble("per_amount");
}
ps = con.prepareStatement("select retirement_gratuity from CAL where emp_id = ?");
ps.setString(1,emp_id);
rst = ps.executeQuery();
if(rst.next())
{
double ret_grat = rst.getDouble("retirement_gratuity");
if(ret_grat >=1000000)
{
continue;
}
}
if(dor.compareTo(eff_date)>0)
{
if(new_da >old_da)
{
ps = con.prepareStatement("select emp_id from AFFECTET where emp_id = ?");
ps.setString(1,emp_id);
rst = ps.executeQuery();
if(!rst.next())
{
ps = con.prepareStatement("insert into upops.AFFECTED (EMP_ID,PREVIOUS_DA,NEW_DA,PREV_GRATUITY,NEW_GRATUITY,REVISION_NO,DONE,EFF_DATE,PAY_COMM,CATEGORY) (select pm.emp_id,pm.da," + new_da + ",c.RETIREMENT_GRATUITY,0,0,'N',to_date('"+eff_date+"','yyyy-MM-dd'),pm.pay_comm,pm.category from upops.pensioner_mast pm ,upops.calculation c where c.emp_id=pm.emp_id and pm.emp_id = '"+emp_id+"')");
int executeUpdate = ps.executeUpdate();
if (executeUpdate > 0) {
ret = CheckUtils.fileMovement(emp_id,usercode , "33", con);
if (ret.equals("SUCCESS")) {
caseCount++;
}
}
}
}
}
else
{
continue;
}
rst.close();
}
ret = "SUCCESS";
if(ret.equals("SUCCESS"))
{
con.commit();
}
}
catch(Exception ex)
{
ex.printStackTrace();;
}
finally
{
try
{
con.close();
}
catch(Exception ex){}
}
If you have to use the Java 7 and above, I prefer you to use try with resources which was introduced in Java 7 new features.
Try-with-resources in Java 7 is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block.
As to your code:
finally
{
try
{
con.close();
}
catch(Exception ex){}
}
Do you notice that ugly double try?
But, if you used the try with resources , close() is automatically called, if it throws an Exception or not, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for your Database connection and resources case.
Eg.: (JDBC with try with resources)
try (Connection con = DriverManager.getConnection(yourConnectionURL);
PreparedStatement ps = createPreparedStatement(con, userId);
ResultSet rs = ps.executeQuery()) {
// process the resultset here, all resources will be cleaned up
} catch (SQLException e) {
e.printStackTrace();
}
private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
String sql = "SELECT id, username FROM users WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, userId);
return ps;
}

passing java string variable in mysql query

How to pass java string variable in sql query .I have done all the JDBC connection .
My sql database query is
sql = "Select *
from production AS cust
INNER JOIN location AS comp
ON cust.location_id = comp.location_id
where comp.name = locationnames AND crop_id =1";
It is not working. However if i do the following code its working
sql = "Select *
from production AS cust
INNER JOIN location AS comp
ON cust.location_id = comp.location_id
where comp.name = "\taplejung"\
AND crop_id =1";
Now tell me how should i pass variable name to the sql query to execute this. Jst tell me how to pass the variable locationnames to comp.name.
My complete java function looks like this: locationCombo denotes item selected in combobox. CropCombo also denotes the same...
public void displayYearwise() throws SQLException, ClassNotFoundException{
//jComboBox4.setSelectedItem("Crops");
//DefaultCategoryDataset dataset = new DefaultCategoryDataset();
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series = new XYSeries("production");
XYSeries series1 = new XYSeries("scat");
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://localhost/data2";
Connection conn;
Statement stmt;
String USER = "root";
String PASS = "";
Object cropname = CropCombo.getSelectedItem();
String cropnames = cropname.toString();
Object locationname = locationCombo.getSelectedItem();
// String locationnames = locationname.toString();
String locationnames = "taplejung";
String pd="paddy ";
System.out.println(cropnames.length()+" "+pd.length());
System.out.println(cropsList);
String sql=null;
if(cropnames.equals("paddy"))
{
//System.out.println();
sql="Select *
from production AS cust
INNER JOIN location AS comp
ON cust.location_id = comp.location_id
WHERE comp.name = "+locationnames+"
AND crop_id =1";
}
else{
sql="SELECT *
FROM `production`
WHERE crop_id = 4
AND location_id = 10";
}
try{
Class.forName(JDBC_DRIVER);
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println(sql);
ResultSet rs=stmt.executeQuery(sql);
while (rs.next()){
//String student = rs.getString("studentname");
String yeartext = rs.getString("year_of_production");
//double value = Double.parseDouble(text);
String productiontext = rs.getString("production_amount");
Double yield = rs.getDouble("yield_amount");
double production = Double.parseDouble(productiontext);
double year = Double.parseDouble(yeartext);
series.add(year,production) ;
series1.add(year,yield) ;
//dataset.addSeries(series);
}
dataset.addSeries(series);
dataset.addSeries(series1);
chartArea.removeAll();
JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset);
// JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled);
// CategoryPlot p = chart.getCategoryPlot();
//XYPlot xyplot = (XYPlot)jfreechart.getPlot();
//http://stackoverflow.com/questions/12417732/jfreechart-with-scroller
ChartPanel chartPanel = new ChartPanel(chart, false);
chartArea.setLayout(new BorderLayout());
chartArea.add(chartPanel, BorderLayout.EAST);
chartArea.add(chartPanel);
SwingUtilities.updateComponentTreeUI(this);
// p.setRangeGridlinePaint(blue);
chartArea.updateUI();
System.out.println("Database created successfully...");
}
catch(SQLException se)
{
//Handle errors for JDBC
System.out.println("Connect failed ! ");
se.printStackTrace();
// JOptionPane.showMessageDialog(MajorUI.this, err.getMessage());
}
}
Use a PreparedStatement and bind the String parameter,
final String sql = "select * from production AS cust INNER JOIN location"
+ " AS comp ON cust.location_id = comp.location_id where "
+ "comp.name = ? AND crop_id = 1";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, "taplejung");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (Exception ignored) {
}
}
}
Edit (Based on your additional code, change it to something like)
PreparedStatement ps = null;
String sql = null;
if (cropnames.equals("paddy")) {
// System.out.println();
sql = "SELECT * FROM `production` AS cust INNER JOIN location AS comp "
+ "ON cust.location_id = comp.location_id WHERE comp.name = "
+ "? AND crop_id = 1";
} else {
sql = "SELECT * FROM `production` WHERE crop_id = 4 AND location_id = 10";
}
ps = conn.prepareStatement(sql);
if (cropnames.equals("paddy")) {
ps.setString(1, locationnames);
}
System.out.println(sql);
ResultSet rs = ps.executeQuery();
String locationnames = "taplejung";
String sql = "Select * from production AS cust INNER JOIN location AS comp ON cust.location_id = comp.location_id where comp.name ='"+ locationnames +"' AND crop_id =1";
Whenever I have to make sql queries I use a library like jdbi to do it. This will allow you to create an interface with different queries. All you have to do is define the interface, create a POJO, and create a mapper between a SQL table and a Java POJO.
The interface would look something like this.
#RegisterMapper(ProductionMapper.class)
public interface ProductionDAO {
#SqlQuery("Select * from production AS cust INNER JOIN location AS comp ON cust.location_id = comp.location_id where comp.name = :name AND crop_id =1")
Production findRow(#Bind("name") String name);
}
The POJO would look something like this.
public class Production {
private VariableTypeA variableA;
// other variables
public Production(VariableTypeA variableA ....) {
this.variableA = variableA;
// set everything else
}
// getters and setters
}
The mapper would look something like this.
public class ProductionMapper implements ResultSetMapper<Production> {
public Production map(int index, ResultSet r, StatementContext ctx) throws SQLException {
return new Production(r.getSomeType("columnName"), ...);
}
}
This design makes it really simple to interact with your database and pass variables as well as making it so that your classes dont violate the SRP
http://jdbi.org/sql_object_overview/
Passing variable is quiet simple in mysql query using java.
Write your query
and write the variable in ""
In my case i am passing 'conition' and 'tablename' dynamically.
Thank you very much have a good day.
#Override
public LinkedList getNameList(String condition, String tableName, String projectName) {
// TODO Auto-generated method stub
String query = "select distinct("+condition+") as name from "+tableName+" ";
//System.out.println(query);
ResultSet rs = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
LinkedList finalList = new LinkedList();
try{
connection = dataSourceAbacus.getConnection();
preparedStatement = connection.prepareStatement(query);
rs= preparedStatement.executeQuery();
while(rs.next()){
finalList.add(rs.getString("name"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(connection !=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(preparedStatement != null){
try{
preparedStatement.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(rs != null){
try{
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return finalList;
}

Categories