SQL command from eclipse using JDBC - java

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.

Related

Invalid Identifier when using LIKE query in Java

I'm trying to execute a LIKE query in Java using prepared statements but I'm getting the following error
ORA-00904: "%12P1A%": invalid identifier
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DataSourceFactory.getConnection();
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, "%12P1A%");
resultSet = statement.executeQuery();
//....
}catch (SQLException e) {
throw new DAOException(e.getMessage());
} finally {
DaoUtil.closeAll(connection, statement, resultSet);
}
May I know why is this incorrect?
For further Information, I'm actually getting '%12P1A%' by some other function so the code is something like
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, getValue());
the query parses to something like
select * from users where userID like '%12P1A%'
but it is throwing MISSING IN or OUT Paramter. Idk why it is not picking the value. Any suggestions?
You could extract the value between '% and %' that you are getting from the input and then create your query as -
statement = connection.prepareStatement("select * from users where userID like '%" + <value-from-some-other-method> + "%'");
If there is an option, ask the method response to be the value directly instead of having it formatted for query parameter.

How to check if the inputted data exist in database

I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!

Java: SQL Query: rs.next() is false after updating a column

I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

Mysql select prepared statement in JAVA [duplicate]

This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
this is my current java program. I need to make a prepared statement and connect to a MySql database.
try {
Connection connect = DriverManager.getConnection(host, username, password);
System.out.println("works fine connected");
/*
*
* */
String Dquery = ("SELECT * FROM ?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book");
System.out.println("mySql statemnt: "+Dquery);
//execute the query, and get a java resultset
ResultSet rs = st.executeQuery();
//iterate through the java resultset
while (rs.next())
{
String id = rs.getString(Column1);
String firstName = rs.getString(Column2);/*
String lastName = rs.getString(Column3);
String dateCreated = rs.getString(Column4);
int isAdmin = rs.getInt (Column5);*/
//print the results
System.out.println(id+"|\t"+firstName/*+"|\t\t"+lastName+"|\t\t"+dateCreated+"|\t"+isAdmin*/);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I cant insert the "lmgs_Book" String into the prepared statement.
Prepared statement is for the column values not for table name.
But you can use placeholder in place of table name and then replacing
that with your tablename.
String Dquery = ("SELECT * FROM $tableName");
Dquery = Dquery.replace("$tableName","lmgs_Book");
PreparedStatement st = connect.prepareStatement(Dquery);
Remove this:
st.setString(1, "lmgs_Book");
Caution:
And what is the advantage compared to
String Dquery = "SELECT * FROM lmgs_Book";? [Recommended]
Answer: No advantage at all. You may embrace potential harms if you use placeholder in table name like above.
(especially since you should not use a variable in the replace call
instead of the literal, since that might make the statement vulnerable
to SQL injection)
try this and Please make sure your queryString column Name must be a varchar in your database.
String Dquery = ("SELECT * FROM tablename where column_name =?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book"); //this line will be set Imgs Books as search Parameter.

Java- select certain rows from column with SQLite

Sorry if the title is not precise.
I am using a custom class to get data from a SQLite database.
For example:
the method below is supposed to return list of users, which are members of a certain department.
Each user in the USER table has a column with id of the department he belongs to.
At the moment I am getting all the users and then comparing their department IDs to the targetID of the department I am looking for.
Is there a way to get just the set of users that have a particular department ID, so that I don't have to check each one's department id?
private List<User> getDepartmentMembers(int targetID) {
List<User> members = new ArrayList<User>();
Connection c = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:TheatroData.sqlite");
c.setAutoCommit(false);
statement = c.createStatement();
ResultSet rs = statement.executeQuery( "SELECT * FROM USERS;" );
while ( rs.next() ) {
int id = rs.getInt(Constants.ID_KEY);
if (id == targetID ){
User tmp = null;
int position = rs.getInt(Constants.POSITION_KEY);
if (position == Constants.DEPARTMENT_HEAD)
tmp = new DepartmentHead();
else if (position == Constants.DEPARTMENT_MANAGER)
tmp = new DepartmentManager();
else if (position == Constants.DEPARTMENT_MEMBER);
tmp = new GruntUser();
tmp.setID(id);
tmp.setName(rs.getString(Constants.NAME_KEY));
tmp.setPosition(position);
tmp.setUsername(rs.getString(Constants.USERNAME_KEY));
tmp.setLastname(rs.getString(Constants.SURNAME_KEY));
tmp.setDepartment(targetID);
tmp.setPassword(rs.getString(Constants.PASS_KEY));
members.add(tmp);
}
}
rs.close();
statement.close();
c.close();
} catch ( Exception e ) {
System.err.println( e + " -in getDepartmentMembers" + e.getClass().getName() + ": " + e.getMessage());
}
return members;
}
I was thinking I need something like this:
ResultSet rs = statement.executeQuery( "SELECT * FROM USERS where department = ?;", targetID );
In an ideal world, you could do it as you wrote:
ResultSet rs = statement.executeQuery( "SELECT * FROM USERS WHERE department = ?;", targetID );
But, executeQuery from JDBC does currently not provide the possibility for argument binding. So you have to use "Prepared Statements".
Instead of
statement = c.createStatement();
ResultSet rs = statement.executeQuery( "SELECT * FROM USERS;" );
do:
prepared = c.prepareStatement("SELECT * FROM USERS WHERE department = ?;");
prepared.setString(1, targetID);
ResultSet rs = prepared.executeQuery();
When you need more than one parameter, you can use a different syntax for replacing it, for example "?001". See SQLite Documentation: C/C++ Interface Section 5.
Also remove the Java coding for your own selection of the right department.
Since the CluelessStudent presented a different solution, involving string concatenation, I want to say the following:
I would definitively discourage string concatenation! You always
should use argument binding and not string concatenation! String
concatenation is a huge security risk, since it can be used for so
called "SQL injection attacks". See Wikipedia: SQL Injection
Yes you pratcially answered your own question. You can also do like this.
String query = "SELECT * FROM USERS where department = (?)";
PreparedStatement statement = c.prepareStatement(sql);
statement.setInt(1, targetId);
ResultSet rs = statement.executeQuery();
while(rs.next()){
//you get only records that have id = targetId
}
//close rs, statement and connection!!!
I was just passing a wrong statement. The correct way:
ResultSet rs = statement.executeQuery( "SELECT * FROM USERS where department = "+targetID+";");

Categories