I want to retrieve a particular column from the database. For a simple Select statement, I can able to able to retrieve a column like below
public String getDbColumnValue(String tableName, String columnName, String applicationNumber) {
String columnValue = null;
try {
PreparedStatement ps = null;
String query = "SELECT " + columnName + " FROM " + tableName +
" WHERE ApplicationNumber = ?;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString(columnName);
return columnValue;
}
}
catch (Exception ex) {
}
return columnValue;
}
But, I'm using alias in my query like below. And this query works fine. How to use this in Java to retrieve a particular column
select S.StatusDesc from application A, StatusMaster S
where A.StatusMasterId = S.StatusMasterId and A.ApplicationNumber = '100041702404'
Any help would be greatly appreciated!
I think you are confusing simple aliases, which are used for table names, with the aliases used for column names. To solve your problem, you can just alias each column you want to select with a unique name, i.e. use this query:
select S.StatusDesc as sc
from application A
inner join StatusMaster S
on A.StatusMasterId = S.StatusMasterId and
A.ApplicationNumber = '100041702404'
Then use the following code and look for your aliased column sc in the result set.
PreparedStatement ps = null;
String query = "select S.StatusDesc as sc ";
query += "from application A ";
query += "inner join StatusMaster S ";
query += "on A.StatusMasterId = S.StatusMasterId ";
query += "and A.ApplicationNumber = ?";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString("sc");
return columnValue;
}
Note: I refactored your query to use an explicit inner join instead of joining using the where clause. This is usually considered the better way to write a query.
Related
Im running the code and keep getting the Resultset is closed, is there something wrong with the loops? The Strings that is taken from the for() has multiple "SUBKATEGORIER" aswell. Pls help me I'm new to Java.
Object[] valt = jList1.getSelectedValues();
for (Object ettVal : valt) {
String enSuperkategori = ettVal.toString();
System.out.println(enSuperkategori);
try {
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT SUBKATEGORIID FROM
SUBKATEGORI JOIN SUPERKATEGORI ON SUPERKATEGORI.SUPERKATEGORIID =
SUBKATEGORI.SUPERKATEGORI WHERE SUPERKATEGORI.SKNAMN ='" + enSuperkategori
+"'");
while(rs2.next());
{
PreparedStatement ps2 = connection.prepareStatement("INSERT
INTO ANVANDARE_SUBKATEGORI (ANVANDARE,SUBKATEGORI) VALUES(?,?)");
ps2.setString(1, angivetAnv);
ps2.setInt(2, rs2.getInt("SUBKATEGORIID"));
System.out.println(rs2.getInt("SUBKATEGORIID"));
ps2.executeUpdate();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
I don't know the exact cause of the error, but my guess is that your first result set is getting closed as soon as you run the inner insert. The good news is that you may run your entire insert using the following single query:
INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI)
SELECT SUBKATEGORIID, SUBKATEGORIID
FROM SUBKATEGORI s
INNER JOIN SUPERKATEGORI sp
ON sp.SUPERKATEGORIID = s.SUPERKATEGORI
WHERE sp.SKNAMN = ?
Your relevant Java code:
String sql = "INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI) ";
sql += "SELECT SUBKATEGORIID, SUBKATEGORIID ";
sql += "FROM SUBKATEGORI s ";
sql += "INNER JOIN SUPERKATEGORI sp ";
sql += "ON sp.SUPERKATEGORIID = s.SUPERKATEGORI ";
sql += "WHERE sp.SKNAMN = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, enSuperkategori);
ps.executeUpdate();
The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();
So I have a method that looks up a foreign key in a database. If the foreign key does not exist it will add an entry into the database. Now what I am doing from that point after inserting the new record, is re-querying again to get the foreign key. Is this overkill or is this the right way to do this? Thanks
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}
Since you are inserting a new row into DB, you have to do a query to get back the auto increment field(id). Currently they way you are doing is workable. But there are few alternatives in query:
Obtaining the id using last_insert_id():
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
Another approach can be doing the MAX over the id column of the table.
I believe these are will be much faster than your query as you are doing string comparison in where clause.
Finally narrowed down the problem, here is what my problem is when i execute a SQL which has 'order by' on that and try to print the result set in Java the result set is not sorted.
But when i execute the SQL separately with my SQL developer, I am seeing the ordered result why is that? Is there any option to solve this?
Below mentioned is method I am using
List getDBValues(short orderBy) throws Exception {
Connection conn = null;
ResultSet rs = null;
List results = nmull;
String sqlStmt = new String();
PreparedStatement ps = null;
try {
conn = Utilities.getConnection(DB);
sqlStmt ="SELECT
COLUMN1,
COLUMN2,
COLUMN3,
FROM SAMPLE_TABLE
WHERE
COLUMN1 IN ('10','15') AND
COLUMN3 IN ('1','2') ORDER BY ? ";
try {
short orderByObj = 0;
if(orderBy < 1){
orderByObj = Short.parseShort(Math.abs(orderBy)+"");
sqlStmt += "DESC";
}else{
orderByObj = orderBy;
}
System.out.println("==================== SQL ==================== \n"+sqlStmt);
ps = conn.prepareStatement(sqlStmt);
ps.setLong(1, orderByObj);
rs = ps.executeQuery();
while (rs.next())
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
catch(SQLException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace()
}
return results;
}
You cannot use a bind variable within the order by statement.
You'll have to append it to the query.
sqlStmt ="SELECT
COLUMN1,
COLUMN2,
COLUMN3,
FROM SAMPLE_TABLE
WHERE
COLUMN1 IN ('10','15') AND
COLUMN3 IN ('1','2') ORDER BY ";
try {
short orderByObj = 0;
if(orderBy < 1){
orderByObj = Short.parseShort(Math.abs(orderBy)+"");
sqlStmt = sqlStmt + " " + orderByObj + " DESC";
}else{
sqlStmt = sqlStmt + " " + orderBy ;
}
System.out.println("==================== SQL ==================== \n"+sqlStmt);
ps = conn.prepareStatement(sqlStmt);
rs = ps.executeQuery();
while (rs.next())
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
There might be problem with you JSP iterations.
Write out the codes you used here. Both i java, jsp.
Use LinkedList kind of collection stuff that stores data with respect to insertion order.
At the risk of being obvious, could it have anything to do with the fact that your SQL query doesn't actually sort the data? Maybe you mean to rewrite with a proper ORDER statement, such as, for example:
SELECT column1, column2 FROM table ORDER BY column1 DESC
Similar question to:
Strange problem with JDBC, select returns null
but people didn't ask for this.
My code:
public int myMethod(String day) throws SQLException{
String sql = "Select count(*) from MyTable WHERE someColumn = " + day;
Connection connection = ConnFactory.get();
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
int ret = -1;
try{
prepareStatement = connection.prepareStatement(sql);
resultSet = prepareStatement.executeQuery(sql);
if(resultSet.next()){
ret = resultSet.getInt(1);
}
}
catch(SQLException sqle){
// closing statement & ResultSet, log and throw exception
}
finally{
// closing statement & ResultSet
}
ConnFactory.kill(connection);
return ret;
}
This code always return 0. I try to log sql before execution and try to run it in SQLdeveloper and get correct value (over 100).
When I remove WHERE, sql = "Select count(*) from MyTable query return number of all rows in table.
I use Oracle 10g with ojdbc-14.jar (last version from maven repo) and Java 6.
day has not been quoted correctly, I would suggest using a prepared statement like a prepared statement as follows:
...
try {
prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
prepareStatement.setString(1,day);
...
is the same as:
sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
with several advantages over the latter (mainly security and performance). See:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
First of all using sql like this is not advisable. Because it leads to SQL injection.
In the future try using like below and use PreparedStatement to execute
String sql = "Select count(*) from MyTable WHERE someColumn = ? "
For your solution did you try
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
karim79 is good answer, you forgot add apostrophe signs in your "day" value
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";