I have a MySQL table with entries already in it and I have it connected to my Java program so it displays the table values whenever the program is run. I'm basically trying to implement a search field where the user can type any attribute's value and all the entries that match that value will be loaded into the table. Then the user will be able to select the right entry that matches and they can edit, or update that entry's information. This would be useful for me particularly when you have entries that have the same value, for instance first name, last name, or zip code.
try {
String sql = "SELECT * FROM donors WHERE donor_id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
String sql = "SELECT * FROM donors WHERE first_name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
The search field only searches for the second query, but not the first, so I can type a name and the matching names will load into the table, but when I try to input an id number, nothing happens. I'm fairly new to this, but I think it has something to do with my resultset object? Not exactly sure though. Any help would be great.
What happens here is that the second result overwrites the first. I think the easiest solution is to use or in the where clause, like this:
String sql = "SELECT * FROM donors WHERE (donor_id = ?) or (first_name = ?)";
ps.setString(1, txtSearch1.getText());
// but of course there are 2 ?'s now, we have to give the value to the second one
// as well
ps.setString(2, txtSearch1.getText());
Due to the way placeholders work in JDBC you'll have to provide a value for each ?.
Related
I am trying to make my program checks if the table name is exist or not by searching letters or words from the table name... for example my tables name are (samAmerica) and (samGermany) I want the program to checks if there is any table name include (sam) word alone.. so when I search using sam word he will show me both tables... I know how to make it check it all but it is not helpful for me because I will be having a lot of same names but different nicknames as a tables.
this is my code where checks all the table name together.. I would appreciate if someone helps me.
public boolean istableNameexist(String un){
boolean uexist = false;
Connection con = myConnection.getconnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = con.prepareStatement("SELECT * FROM information_schema.tables WHERE TABLE_NAME = ?");
ps.setString(1,name.getText()+faturanumarasi.getText());
rs = ps.executeQuery();
if (rs.next()){
uexist = true;
}
} catch (Exception e) {
System.out.println("wrong");
}
return uexist;
}
You can try using like operator
SELECT * FROM information_schema.tables WHERE TABLE_NAME LIKE concat('%',?,'%')
https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
I have a program that selects from a database given a table and column string.
public void selectAllFrom(String table, String column){
String sql = "SELECT ? FROM ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)){
pstmt.setString(1, column);
pstmt.setString(2, table);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getString(column));
}
} catch (SQLException e){
System.out.println(" select didn't work");
System.out.println(e.getMessage());
}
}
For some reason it is not working and it is going right to catch
Here is the connect() function as well:
private Connection connect(){
Connection conn = null;
// SQLite connection string
String url = "jdbc:sqlite:C:/sqlite/db/chinook.db";
try{
// creates connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established");
} catch (SQLException e){
System.out.println(e.getMessage());
System.out.println("Connection didn't work");
}
return conn;
}
I know the problem is not with the database because I'm able to run other select queries without parameters. It is the parameters that are giving me the problem. Can anyone tell what the problem is?
A table or column name can't be used as a parameter to PreparedStatement. It must be hard coded.
String sql = "SELECT " + column + " FROM " + table;
You should reconsider the design so as to make these two constant and parameterize the column values.
? is a place holder to indicate a bind variable. When a SQL statement is executed, database first checks syntax, and validates the objects being referenced, columns and access permission for specified objects (i.e metadata about objects) and confirms that all are in place and valid. This stage is called parsing.
Post parsing, it substitutes bind variables to query and then proceeds for actual fetch of results.
Bind variables can be substituted in any place in query to replace an actual hard coded data/strings, but not the query constructs them selves. It means
You can not use bind variables for keywords of sql query (ex: SELECT, UPDATE etc.)
You can not use bind variables for objects or their attributes (i.e table names, column names, functions, procedures etc.)
You can use them only in place of a otherwise hard coded data.
ex: SELECT FIRST_NAME, LAST_NAME, 'N' IS_DELETED FROM USER_DATA WHERE COUNTRY ='CANADA' AND VERIFIED_USER='YES'
In above sample query, 'N','CANADA' and 'YES' are the only strings which can be replaced by a bind variable, not any other word.
Using bind variable is best practice of coding. It improves query performance (when used with large no. of queries in tuned database products like Oracle or MSSQL) and also protects your code against sql injection attacks.
Constructing query by concatenating strings (especially data part of query) is never recommended way. You can still construct a query by concatenation for other parts like table name or column name as long as those strings are not directly taken from input.
Below example is acceptable:
query = "Select transaction_id, transaction_date from ";
if (isHistorical(reportType)
{ query = query + "HISTORY_TRANSACTIONS" ;}
else
{query = query + "PRESENT_TRANSACTIONS" ; }
recommended practice is to use
String query_present = "SELECT transaction_id, transaction_date from PRESENT_TRANSACTIONS";
String query_historical = "SELECT transaction_id, transaction_date from HISTORY_TRANSACTIONS";
if (isHisotrical(reportType))
{
ps.executeQuery(query_historical);
}else{
ps.executeQuery(query_present);
}
what is the best way to check if the user is exist
i have wrote this code
try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();
}
my friends told me that this is stupid query
and i should do like this
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");
Your friend is right. You can check if row exists by query:
SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)
As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine.
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore.
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are.
When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection.
But
Inserting a new user to the database is not the right way to do user validation.
You can do something like this example:
String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setString(2, "1234");
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
//You will need user information to render dashborad of your web application
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}
Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
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.