Is there a simple way to add something to PreparedStatement?
For example:
ps = connection.prepareStatement("SELECT DISTINCT nazivpredmeta, iddokumenta, nazivdokumenta, putanja, datumskeniranja FROM skeniranidokumenti , predmet WHERE "
if(osnovnibroj!=null){
ps.add("predmet.osnovnibroj=? ");
ps.setObject(1, osnovnibroj);
}
if(iddepartmana!=null){
if(osnovnibroj!=null){
ps.add("AND skeniranidokumenti=? ");
ps.setObject(1, iddepartmana);
}else{
ps.add("skeniranidokumenti=? ");
ps.setObject(1, iddepartmana);
}
I know that there is not add method, my question is: is there something i can use?
No you can't.. Simply you can do like this:
String query="SELECT DISTINCT nazivpredmeta, iddokumenta, nazivdokumenta, putanja, datumskeniranja FROM skeniranidokumenti , predmet WHERE ";
if(osnovnibroj!=null){
query=query+"predmet.osnovnibroj=? ";
ps = connection.prepareStatement(query);
ps.setObject(1, osnovnibroj);
}
You could construct your SELECT statement using a StringBuilder, and then pass the completed string to connection.prepareStatement().
StringBuilder sb = new StringBuilder("SELECT DISTINCT nazivpredmeta, iddokumenta, nazivdokumenta, putanja, datumskeniranja FROM skeniranidokumenti , predmet WHERE TRUE");
if (osnovnibroj != null)
{
sb.append(" AND predmet.osnovnibroj = ?");
}
if (iddepartmana != null)
{
sb.append(" AND skeniranidokumenti = ?");
}
ps = connection.prepareStatement(sb.toString());
if (iddepartmana != null)
{
if (osnovnibroj != null)
{
ps.setObject(1, osnovnibroj);
ps.setObject(2, iddepartmana);
}
else
{
ps.setObject(1, iddepartmana);
}
}
else if (osnovnibroj != null)
{
ps.setObject(1, osnovnibroj);
}
Note that I've used the WHERE TRUE trick to simplify the logic of constructing the WHERE clause.
Related
i have built quiz web project.
i want to insert below mentioned test question into database. i am writing this question in html textarea, then getdata from html with inner.html :
but when i select this question from database it looks like that, it is hard readable, carelessly written:
help me make above mentioned tests readable.
my sql insert code :
public void addtest(TestModel test) throws Exception {
Connection c = null;
PreparedStatement ps = null;
String sql = "INSERT INTO TEST_TABLE (QUESTION,A,B,C,D,E,QUESTION_TYPE,SCORE,SUBJECT, CORRECT, Variant) " +
" VALUES (?,?,?,?,?,?,?,?,?,?,?) ";
try {
c= DbHelper.getConnection();
if(c != null) {
ps = c.prepareStatement(sql);
ps.setString(1,test.getQuestion());
ps.setString(2,test.getOptionA());
ps.setString(3,test.getOptionB());
ps.setString(4,test.getOptionC());
ps.setString(5,test.getOptionD());
ps.setString(6,test.getOptionE());
ps.setString(7,test.getQuestionType());
ps.setLong(8,test.getScore());
ps.setLong(9,test.getSubjectId());
ps.setString(10,test.getCorrectOption());
ps.setInt(11,test.getVariant());
ps.execute();
} else {
System.out.println("Connection is null");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c,ps,null);
}
}
my sql select code :
public TestModel getquestionlist(long firstpage,int variant) throws Exception {
TestModel testdata = new TestModel();
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql =" SELECT TE.ID,TE.QUESTION,TE.A,TE.B,TE.C,TE.D,TE.E,TE.F,TE.G,TE.QUESTION_TYPE,TE.SCORE,S.NAME as Subject,TE.CREATE_DAY,TE.CORRECT, d.value, TE.Variant FROM TEST_TABLE TE " +
"INNER JOIN SUBJECT S ON S.ID = TE.SUBJECT " +
"inner join dictionary d on d.ID = TE.Variant " +
"WHERE TE.ACTIVE =1 AND S.ACTIVE =1 AND TE.Variant = ? " +
"LIMIT ?,1; ";
try {
c = DbHelper.getConnection();
if (c != null) {
ps = c.prepareStatement(sql);
ps.setInt(1,variant);
ps.setLong(2, firstpage);
rs = ps.executeQuery();
while (rs.next()) {
testdata.setId(rs.getLong("ID"));
testdata.setQuestion(rs.getString("QUESTION"));
testdata.setOptionA(rs.getString("A"));
testdata.setOptionB(rs.getString("B"));
testdata.setOptionC(rs.getString("C"));
testdata.setOptionD(rs.getString("D"));
testdata.setOptionE(rs.getString("E"));
testdata.setOptionF(rs.getString("F"));
testdata.setOptionG(rs.getString("G"));
testdata.setQuestionType(rs.getString("QUESTION_TYPE"));
testdata.setScore(rs.getLong("SCORE"));
testdata.setTestSubject(rs.getString("Subject"));
testdata.setCreateDate(rs.getDate("CREATE_DAY"));
testdata.setCorrectOption(rs.getString("CORRECT"));
testdata.setVariant(rs.getInt("Variant"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c, ps, rs);
}
return testdata;
}
You can use <br/> to break line :
"1: public class WaterBottle { <br/>"
So in the moment of getting the result you can concatenate your result with <br/> for example :
testdata.setQuestion(rs.getString("QUESTION") + "<br/>");
Here is sample code ...
Statement stmt = con.createStatement();
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println(query); // displaying only `
ResultSet rs = stmt.executeQuery(query);
System.out.println(query);
while (rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
If String passed Instead of passing variable then it works ...like
ResultSet rs = stmt.executeQuery("select * from work_product where product_name ='product' ");
I also used preparedStatement...but not working ...
PreparedStatement statement = con.prepareStatement("select * from work_thing_db.work_product where product_name = ? ");
statement.setString(1,ch);
Here is full code ....
#FXML protected void keyReleased(KeyEvent evt)throws Exception {
//SetTimer();
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
}
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Using : IntelliJ IDEA 14 CEOutput :
Enter key Fired
product
In dbSearch
Concat String :product
'
kindly point out my mistake ... i'm new in java... and further i need to use like and or with it .... please provide answer with explanation... Thanks in advance.
It's possible there is no match in the data. You could run a non filtered query first and see what values you have for product_name in the table.
I haven't thought of it....
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
ch = ch.trim().toString(); // trim and type cast ... its working
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Now it is fetching data properly ...
There is something wrong in the way you concatenate the string
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
so when the user will enter "ENTER" (can be \n or \r) you will concatenate before the condition of the key value so concateString will always contain your string + "ENTER" (i.e. the carriage return). Thats the reason you only get the quote when you print your query
Not to modify much of your code, you can do
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
} else {
concateString = concateString + ch; //concateString has scope
}
}
and so you will pass the correct string
I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
Hello and thank you for reading my post.
I have a PostgreSQL table "t" with a column "c" which type is "character varying(32)".
Values in this column look like this: "2014100605".
I am using the "MAX()" aggregate function to retrieve the maximum value in this column.
SELECT MAX(c) AS max FROM t;
In Java, if I prepare the query above, get a "resultSet" object and send it the getString("max") message, I get max = null.
If I send it the getInt("max") method instead, I get the result I'm expecting, something like "2014100605".
Is this normal behavior?
Am I really allowed to do this or is it by chance I'm getting the expected result?
Is "MAX()" actually using the lexicographical order?
Best regards.
A bit of Java code:
s_preparedSqlQuery =
"SELECT MAX(quotinv_nro) AS quotinv_nro_max "
+ "FROM imw_quotation_invoice "
+ "WHERE quotinv_type = ? "
+ "AND quotinv_nro LIKE '" + s_quotinvDate + "%'";
preparedStatement = m_connection.prepareStatement(s_preparedSqlQuery);
preparedStatement.setString(1, s_quotinvType);
resultSet = preparedStatement.executeQuery();
if(resultSet != null)
{
if(resultSet.next())
{
// s_quotinvNroMax = resultSet.getString("quotinv_nro_max");
n_quotinvNroMax = resultSet.getInt("quotinv_nro_max");
// if(s_quotinvNroMax == null)
if(n_quotinvNroMax == 0)
{
n_nbQuotinvsThisSameDate = 0;
return n_nbQuotinvsThisSameDate;
}
else
{
s_quotinvNroMax = Integer.toString(n_quotinvNroMax);
n_length = s_quotinvDate.length();
s_currentMaxNro = s_quotinvNroMax.substring(n_length - 1);
n_nbQuotinvsThisSameDate = Integer.valueOf(s_currentMaxNro);
}
}
}
If you are hitting on a unique Id column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(UniqueId) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
if (rs2.next())
{
maxID = rs2.getInt(1);
}
If you are hitting on any other non-key column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(ColumnValue) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
while (rs2.next())
{
maxID = rs2.getInt(1);
}