I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}
Related
First I am going to try using query to retrieve the int min_stock single cell using the item description. Then put that value into a variable. I want to be able to have the variable minStock to be equal to a number. I want to use it to make operations in my program.
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
ResultSet minS = cm.executeQuery("SELECT min_stock FROM items WHERE item_description = '"+item+"'");
int minStock = minS.getInt("min_stock");```
you are choose wrong way to use PrepareStatment.
you have two option to do :
1:
String sql = "SELECT min_stock FROM items WHERE item_description = ?";
PreparedStatement cm = con.prepareStatement(sql);
cm.setString(1, item);
ResultSet rs = cm.executeQuery();
2:
String sql = "SELECT min_stock FROM items WHERE item_description = '" + item + "'";
ResultSet rs = con.createStatement().executeQuery(sql);
and then
if (rs.next())
int minStock = rs.getInt("min_stock");
else
//not found any match row in DB table
Try this
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
cm.setString(1,item);
ResultSet minS = cm.executeQuery();
if(minS.next()){
int minStock = rs.getInt("min_stock");
}
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
Forgot to add this in the beginning of the code!
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.
This is a small piece of my code. Basically, i do not know how to print my ResultSet or turn it into string.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state = con.createStatement();
String query = "SELECT description FROM topics WHERE title = '" + title + "'";
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results = state.executeQuery(query);
// selects * of the rows from "comment" table where the topic equals the selected title.
ResultSet results2 = state.executeQuery(query2);
desc = results.toString();
}
You can not convert ResultSet to string neither you can print directly from ResultSet.
Following code may help you.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state1 = con.createStatement();
Statement state2 = con.createStatement();
String query1 = "SELECT description FROM topics WHERE title = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results1 = state1.executeQuery( query1 );
while( results.next() ){
System.out.println( results1.getString( "description" );
}
// selects * of the rows from "comment" table where the topic equals the selected title.
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
ResultSet results2 = state2.executeQuery( query2 );
while( results2.next() ){
System.out.println( results2.getString( 1 ); // here 1 is tables 1st column
System.out.println( results2.getString( 2 ); // here 2 is tables 2nd column
}
} Exception( SQL e){
e.printStackTrace();
}
I need to erase duplicates in Object example[]
And Object example is filled like this:
final Object example[] = new Object[rowCount];
try{
int row = 0;
Statement st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM Table1");
while(rs.next()){
example[row] = rs.getString("Name");
row++;
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "DBComboBoxFill error: " + e);
}
And i need it for:
JComboBox combobox = new JComboBox(example)
I know how to do that whit Integers, 1st sort them, then check whit if statement and erase. I don't know, maybe i can do it whit ArrayList, but will the ComboBox get values from ArrayList?
If the only column you want is Name (which is what it looks like from the code) then you can instead retrieve just that column in the query, and then you can use DISTINCT to avoid duplicates (as suggested by SubOptimal).
That is, change the query from SELECT * FROM Table1 to SELECT DISTINCT Name FROM Table1 as shown below.
final Object example[] = new Object[rowCount];
try{
int row = 0;
Statement st = conn.createStatement();
rs = st.executeQuery("SELECT DISTINCT Name FROM Table1");
while(rs.next()){
example[row] = rs.getString("Name");
row++;
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "DBComboBoxFill error: " + e);
}
I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.