I want to search some data from database and set it to jtable. So far I have written this code:
try
{
String sql="select * from hotelinfo where Hotel_Name=?;
pst=conn.prepareStatement(sql);
pst.setString(1,searchtxt.getText());
rs=pst.executeQuery();
hotelinfo.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
this code is working but gives only one row i want whole rows which is related to my search
As to your question, you should use like keyword in your select query instead of = sign.
Try with below code:
String sql = "select * from hotelinfo where Hotel_Name LIKE ?";
pst= connection.prepareStatement(sql);
pst.setString(1, "%" + searchtxt.getText() + "%");
rs= preparedStatement.executeQuery();
Related
I am implementing a search method, i want to search a data in a Jtable ( wich contains 2 columns id and name) based in id and name both. Till now I can search using just one of, id or name but cannot do that using them both. I tried a solution, but it is not working it just search for the last one ( id or name). For example if i start with try and catch by name and then id, it only goes with id search. And if I start with id and the name, it searches just by name. Can u help me please.
The code :
`private void textField1KeyReleased(java.awt.event.KeyEvent evt) {
PreparedStatement pst=null;
ResultSet rs=null;
if (textField1.getText().length() > 0){
try{
String sql = "select * from compte_utilisateur where nom=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
**catch(Exception e){JOptionPane.showMessageDialog(null, e);}
try{
String sql = "select * from compte_utilisateur where id_utilisateur=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
else update_table();
}`**
Use just one SQL call passing the same value from the field twice
select * from compte_utilisateur where nom=? or id_utilisateur=?
You should to add jar/folder this rs2xml.jar in your project
String sql="Select * From Inventarizimi where Regjistrimi=?";
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con= (Connection) DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","Inventarizimi"); PreparedStatement preStatement = con.prepareStatement(sql); preStatement.setString(1, txtRegjistrimi.getText());
ResultSet result = preStatement.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(result));
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.
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
I have a table inside consist of variable like Username, ContactNo, Date, Name.
And i would like to do a update for Username and ContactNo only to the original record in the database.
How can i make use of update sql statement to do it?
Below is my SELECT sql statement.
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","mysql");
ps = con.createStatement();
SQL_Str="Select username,numberOfBid from customer where username like ('" + UName +"')";
//SQL_Str="Select * from customer";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString("username").toString();
dbbid=rs.getInt("numberOfBid");
//UName2 = rs.getString("username").toString();
UName2 = username;
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}
http://dev.mysql.com/doc/refman/5.0/en/update.html
And please study...
Here is a quick and dirty solution: when you have modified your values, just add something like this
String updSQL = "udate table set numberOfBid = " + dbbid + " where user = " + UName;
ps.executeUpdate(updSQL);
There are however 1000 improvements you can make such using prepared statementsand placeholders:
String updSQL = "udate table set numberOfBid = ? where username like ?";
PreparedStatement pstmt = con.prepareStatement(updSQL);
pstmt.setInt(0, dbbid);
pstmt.setString(1, UName);
pstmt.execute();
May I suggest you to have a look at Hibernate, Spring JDBC, JPA... which are on a much higher level than JDBC is.
I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.
You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it