passing java string variable in mysql query - java
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;
}
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; } }
Java/Groovy and MySQL: Checking if row exists in table
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(); } }
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'
Java SQL Query Resultset always returns null can't find solution
I am trying to check if a user entered Username and password matches one in my data base however what ever I try the result set still comes up null. the sql varible is set to the username and the pass is set to the password however when ever i enter the correct details it shows up with no results public boolean Login(){ boolean valid = true; try { String stmt = "SELECT * From TBLUser where User = ? and Password = ? ;"; PreparedStatement pstmt = conn.prepareStatement(stmt); pstmt.setString(1, sql); pstmt.setString(2, pass); ResultSet rs = pstmt.executeQuery(); if(!rs.next()){ valid = false; } } catch (SQLException e) { System.err.println("Error: "+e); } return valid; }
Also, better practice: public boolean Login(String asql, String apass){ boolean valid = true; PreparedStatement pstmt = null; ResultSet rs = null; try { String stmt = "SELECT * From TBLUser where User = ? and Password = ? "; pstmt = conn.prepareStatement(stmt); pstmt.setString(1, asql); pstmt.setString(2, apass); rs = pstmt.executeQuery(); valid = (!rs.next()); } catch (SQLException e) { e.printStaceTrace(); } finally { // cleanup try { rs.close(); } catch (Exception ex) {} try { ps.close(); } catch (Exception ex) {} } return valid; }
Use unit cap with " " to save your column-Table like Create Table "TBLUser"{ "User" char... "Password"... } similarly, your select query will change String stmt = "SELECT * From \"TBLUser\" where \"User\" = ? and \"Password\" = ? " This should work.
The problem with the application is not the code but the database as User one of the column names is a reserved word so this change fixed the problem thanks to #Grayson for all the help public boolean Login(){ boolean valid = true; try { String stmt = "SELECT * From TBLUser where UserName = ? and Password = ? ;"; PreparedStatement pstmt = conn.prepareStatement(stmt); pstmt.setString(1, sql); pstmt.setString(2, pass); ResultSet rs = pstmt.executeQuery(); if(!rs.next()){ valid = false; } } catch (SQLException e) { System.err.println("Error: "+e); } return valid; }
How to use prepared statement
Someone has suggested to use prepared statement but I don't know how to use it. What changes do I have to do in my code? try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("\n Driver loaded"); Connection con = DriverManager.getConnection("jdbc:odbc:wanisamajDB"); Statement stmt = con.createStatement(); System.out.println("statement is created"); // System.out.println(Integer.parseInt(cbregn.getSelectedItem().toString())); String qry = " UPDATE Registration1 SET RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ; stmt.executeUpdate(qry); JOptionPane.showMessageDialog(null,"RECORD IS UPDATED SUCCESSFULLY "); System.out.println("QUERY"); // cbregn.setEditable(false); cbnm.setEditable(false); tfplace.setEditable(false); tfkul.setEditable(false); tfgotra.setEditable(false); tfswami.setEditable(false); taraddr.setEditable(false); tfpcd.setEditable(false); tfstdcode.setEditable(false); tftele.setEditable(false); tfmno.setEditable(false); tfemail.setEditable(false); tfweb.setEditable(false); tfedu.setEditable(false); tfbrch.setEditable(false); cbbldgrp.setEditable(false); con.close(); stmt.close(); } // catch(SQLException eM) // { // JOptionPane.showMessageDialog(null,"RECORD IS NOT FOUND "); // } catch(Exception et) { et.printStackTrace(); // System.out.println("error:"+et.getMessage()); }
see example Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack. Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user. This entails using functions that escape all of the necessary trouble characters, such as the single quote, double quote, and backslash characters. This is unnecessary when dealing with prepared statements. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.
In your code instead of this: String qry= " UPDATE Registration1 set RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ; stmt.executeUpdate(qry); try this: String qry= " UPDATE Registration1 set RegistrationNo = ?,SeniorPerson = ?, NativePlace = ?,Kul = ?, Gotra = ?,KulSwami = ?, ResidensialAddress = ?, PinCode = ?, STDcode = ?,TelephoneNo = ?, MobileNo = ?, Email = ?,Website =?,Education =?,Branch =?,BloodGroup =? where SeniorPerson=?" ; PreparedStatement updateQry = con.prepareStatement(qry); updateQry.setString(1,cbregn.getSelectedItem()); updateQry.setString(2,cbnm.getSelectedItem()); updateQry.setString(3,tfplace.getText()); updateQry.setString(4,tfkul.getText()); updateQry.setString(5,tfgotra.getText()); updateQry.setString(6,tfswami.getText()); updateQry.setString(7,taraddr.getText()); updateQry.setString(8,tfpcd.getText()); updateQry.setString(9,tfstdcode.getText()); updateQry.setString(10,tftele.getText()); updateQry.setString(11,tfmno.getText()); updateQry.setString(12,tfemail.getText()); updateQry.setString(13,tfweb.getText()); updateQry.setString(14,tfedu.getText()); updateQry.setString(15,tfbrch.getText()); updateQry.setString(16,cbbldgrp.getSelectedItem()); updateQry.setString(17,cbnm.getSelectedItem().toString()); updateQry.executeUpdate():
public class UpdatesRecords{ public static void main(String[] args) { System.out.println("Updates Records Example through Prepared Statement!"); Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/jdbctutorial","root","root"); try{ String sql = "UPDATE movies SET title = ? WHERE year_made = ?"; PreparedStatement prest = con.prepareStatement(sql); prest.setString(1,"Sanam We wafafa"); prest.setInt(2,2005); prest.executeUpdate(); System.out.println("Updating Successfully!"); con.close(); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } } catch (Exception e){ e.printStackTrace(); } } } please use above code as reference and change your code