searching from database - java

private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
if(tf_rmid.getText().length()==11){
JOptionPane.showMessageDialog(null,"REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select bk_det.rm_id from bk_det inner join bk_rep on bk_det.rm_id = bk_rep.rm_id WHERE rm_id = ?");
String rm = tf_rmid.getText().trim();
stmt.setString(1, ""+(rm));
while(rs.next()){
int i = rs.getString("RM ID");
String fn = rs.getString("First Name");
String ln = rs.getString("Last Name");
String title = rs.getString("Title");
String city = rs.getString("City");
txtFirstName.setText(fn);
txtLastName.setText(ln);
txtTitle.setText(title);
txtCity.setText(city);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
JOptionPane.showMessageDialog(null,"PLEASE ENTER VALID REMITTANCE ID!");
}
}
I am trying to search values from my database using the select statement but when i am trying to get the value for ? for the where option i am getting error i think its a syntax mistake can ny one please help???

Execute with this,
select bk_det.rm_id from bk_det inner join bk_rep
on bk_det.rm_id = bk_rep.rm_id WHERE bk_det.rm_id = ?
Probably you are missing table name in where clause

It appears a bit odd that you are setting the parameter to the Statement AFTER you execute the query.
Also
int i = rs.getString("RM ID");
this does not compile (if rs is a java.sql.ResultSet instance)

Use a prepared Statement:
String query = "select bk_det.rm_id from bk_det inner join bk_rep on bk_det.rm_id = bk_rep.rm_id WHERE rm_id = ?";
try {
PreparedStatement preps = con.prepareStatement(query);
preps.setString(1, ""+(rm));
preps.execute();
...

Related

Right syntax for concat on derby

I am trying to use concat with a Derby database query. But i get syntax error. How can I use concat in Derby?
The below code is for search purpose
public ArrayList <Tablearray>ListUsers(String ValToSearch){
ArrayList <Tablearray> usersList = new ArrayList <Tablearray>();
Statement st;
ResultSet rs;
try {
Connection con = getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM ABYP WHERE CONCAT(Id_Search, Tyl, Apothkh, Parathrhseis,Ti) LIKE '%"+ValToSearch+"%'";
//String searchQuery = "SELECT * FROM ABYP WHERE ||CONCAT|| (Id_Search) LIKE '%||"+ValToSearch+"||%'";
//String searchQuery = "SELECT *FROM ABYP where ID_SEARCH =? ";
rs = st.executeQuery(searchQuery);
Tablearray tablearray;
while (rs.next()){
tablearray = new Tablearray (
rs.getString("Id_Search"),
rs.getString("Tyl"),
rs.getString("Apothkh"),
rs.getString("Parathrhseis"),
rs.getString("Ti")
);
usersList.add(tablearray);
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return usersList;
}

how i can search in database using jTextField

hi every one i have write program that connect to database i create jTextField and jTable my question is how i can use the jTextField to serch in database and view in jTable the code i try is below
try{
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
Connection con = DriverManager.getConnection( host, uName, uPass);
String sql = "Select * from ITEMB where ITEM '"+asdf.getText()+"'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String pr = rs.getString("PRISE");
String it= rs.getString("ITEMNAME");
String itm = rs.getString("ITEM");
String[] data = {pr, it, itm};
tabMode.addRow(data);
double price = Double.parseDouble(rs.getString("prise"));
totalpay = price + totalpay;
++rowCount;
}
}
catch (Exception e) {
//ignore
}
jTextField3.setText(String.valueOf(totalpay));
}
Don't ignore the Exception. How to you expect to debug your SQL if you don't display error messages???
I would guess the problem is you are missing an "=" from your select statement (ie. "ITEM = asdf.getText()").
However, the better way to use SQL is to use a PreparedStatement so you don't have to worry about all the delimiters. So the SQL might be something like:
String sql = "Select * from ITEMB WHERE ITEM = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, asdf.getText() );
stmt.executeQuery();
stmt.close();
It is much easier to read an maintain.

SQL queries in Java: (JDBC) How to use the SELECT statement?

MysqlDatabase
This is my query to connect to my database.
SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam
FROM speler
WHERE Spel_Naam = ?
I work in the console of netbeans. When I want to show the records of table Speler with the Spel_Naam.
In the console I want to type a primary key of the table Spel and then it shows me the records of the table Speler in the console. How can I do this.
Like WHERE Spel_Naam = ?
The question mark need to be the name that I typed in
Is the select statement correct? I want to type the Spel_Naam in the console and then It must connect to the database and give me the records of table Speler. How can I do this?
public class SpelerMapper
{
private final static String LEES_SPELERS_SQL = "SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam FROM speler WHERE Spel_Naam = ?";
public List<Speler> geefSpelers()
{
List<Speler> spelerLijst = new ArrayList<Speler>();
Statement statement;
Connection connection = PersistentieController.getInstance().getConnection();
try
{
statement = connection.createStatement();
// query database
ResultSet resultSet = statement.executeQuery(LEES_SPELERS_SQL);
while (resultSet.next())
{
String naam = resultSet.getString("naam");
String kleur = resultSet.getString("kleur");
int sector = resultSet.getInt("sector");
int aantalZilverstukken = resultSet.getInt("aantalZilverstukken");
Speler speler = new Speler(naam ,kleur, sector , aantalZilverstukken);
spelerLijst.add(speler);
}
statement.close();
return spelerLijst;
} catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
Use PreparedStatements:
String LEES_SPELERS_SQL = "SELECT ... WHERE Spel_Naam = ?";
PreparedStatement prepStmt = con.prepareStatement(LEES_SPELERS_SQL);
prepStmt.setString(1, naam);
ResultSet rs = prepStmt.executeQuery();
Additional note: while being another option, concatenation of the SQL query is an unsafe way of doing the same task. Refer to this article for more info.

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

How do you access the value of an SQL count () query in a Java program

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.
I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
Use aliases:
SELECT COUNT(*) AS total FROM ..
and then
rs3.getInt("total")
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
I have done it this way (example):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r#r.com"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}

Categories