JAVA: get cell from table of mysql - java

I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;

Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}

You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}

Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.

Related

getProcedures and getFunctions return the same ResultSet

I am trying to drop all the functions and procedures in my DB through java.
My current code is like so:
Class.forName(driver);
Connection conn = getConnectionToDB();
String itemName;
ResultSet rs = getResultSetForItem(item);
String upperCaseItem = item.toUpperCase();
while (rs.next()) {
itemName = rs.getString(upperCaseItem + "_NAME");
// Procedure and function names come with a grouping ID, remove it
if (item.equals("procedure") || item.equals("function"))
itemName = itemName.substring(0, itemName.indexOf(";"));
stmt = conn.createStatement();
stmt.executeUpdate(query + " " + itemName);
}
Where item is once "function" and once "procedure". Also, the query variable is set correctly to be "DROP FUNCTION" or "DROP PROCEDURE" respective to the execution.
The method of getResuletSetForItem:
Class.forName(driver);
Connection conn = getConnectionToDB();
DatabaseMetaData md = conn.getMetaData();
switch (item.toLowerCase()){
case "function":
rs = md.getFunctions("LDMS", "dbo", "%");
break;
case "procedure":
rs = md.getProcedures("LDMS", "dbo", "%");
break;
}
return rs;
What happens is, I get the resultset as functions or procedures according to what I am asking for. BUT it returns also the records for the other kind (Meaning, if I asked for a ResultSet of functions, I also get the procedures as well).
This of course causes an exception when I try to, for example, execute "DROP FUNCTION X" where X is actually a stored procedure.
Although you don't explictly say so, it looks like you might be using the MS SQL Server driver for Java.
From the documentation it looks like the getFunctions and getProcedures methods both return a list of functions and procedures. You need to evaluate the FUNCTION_TYPE column to determine which is which.
The type of the function. It can be one of the following values:
SQL_PT_UNKNOWN (0)
SQL_PT_PROCEDURE (1)
SQL_PT_FUNCTION (2)

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

need to retrieve a database row value via sql based on values retrieved via previous sql query in java

My code goes something like this
DataBaseUtil dbBaseUtil=new DataBaseUtil();
Connection con=dbBaseUtil.getConnection();
String query="select case_id, ticket_id from VAPP_ITEM where
(person1_alt_email='" + username +"') and ticket_type='Service Request' and ticket_status not in ('Closed','Resolved')";
ResultSet rs=dbBaseUtil.getDbResultSet(query);
List<String> tickets=new ArrayList<String>();
while(rs.next())
ticket.add(rs.getString("case_Id")+"-"+rs.getString("ticket_Id"));
MyTicketUtil.searchAndOpenTicket(webui, "", tickets.get(0));
Now, once I get the element "tickets(0)", I perform some operations on it, and after the operations are performed, I need to retrieve ticket_status for the ticket on which the operations were performed - tickets(0).
However, to query the database, I need case_id and ticket_id for tickets(0). How can it be done?
I tried creating two ResultSets and a query post operations like below:
while(rs1.next())
quer1 = "select ticket_status from VAPP_ITEM where case_id=rs.getString(1) and ticket_id = rs.getString(2)";
But this is not working - console shows below error:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot find either column "rs" or the user-defined function or aggregate "rs.getString", or the name is ambiguous.
You have included rs.getString() into string literal.
You should use PreparedStatement for such things:
quer1 = "SELECT ticket_status FROM vapp_item WHERE case_id=? AND ticket_id = ?";
PreparedStatement pstm = conn.prepareStatement(quer1);
while (rs1.next())
{
pstm.setString(1, rs.getString(1));
pstm.setString(2, rs.getString(2));
rs2 = pstm.executeQuery();
...
}

SQL command from eclipse using JDBC

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.

Prepared statement for MySQL so that it would pick a row containing the highest Timestamp for column that would be greater from given parameter?

How to write a Java prepared statement for MySQL so that it would pick a row containing the highest Timestamp value from a column that would be greater from given parameter?
I got as far as:
SELECT * FROM table WHERE timestamp_col=(SELECT MAX(timestamp_col) FROM table)
But how to convert it to prepared statement?
Since there's not really a parameter, it's pretty simple:
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://<server>:3306/<db>","<login>","<pass>");
try{
String sql = "SELECT * FROM table WHERE timestamp_col=(SELECT MAX(timestamp_col) FROM table)";
prest = con.prepareStatement(sql);
// prest.setInt(1,12000); // example of using a parameter for prepared statement
// parameters go in the SQL as ?
ResultSet rs1 = prest.executeQuery();
} catch( SQLException s ) { /* etc */ }
You don't need a parameter if you're just asking for a MAX(). It's perfectly safe.

Categories