select same value from N rows in a mysql database - java

I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.

You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it

Related

ResultSet is closed, only prints the first "SUBKATEGORI"

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();

Java - Sql query with Alias

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.

Using variables to create SQL statements

I'm trying to make a sql query builder type program that uses user input data to build custom queries for the table
so far i have
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
// preparedStmt.setString (2, t2);
// preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
So it connects and everything fine but it doesnt execute the query saying something wrong with the sql syntax for values(?,?,?)
Any help would be awesome thanks guys!!
Carl
Try this, Changes in query and in setting prepared statement parameters,
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between ? and ?"
+ "AND id = ?";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
preparedStmt.setString (2, t2);
preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
Share the exact error if doesn't work for you.
Change this:
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
According to the database syntax that you are using. For example if you using a webserver with Mysql go and type the query to see where the typo is. (if you using mysql it needs dancers to every table)
First, you seem to have edited this method many times to try fix the problem, which has left it in a confused state.
remove the "values (?)" from the sql statement, it does not belong here, it seems to be left over from a prepared insert statement.
call preparedStmt.executeQuery() with zero arguments, you have already supplied it with the sql string and only call it ONCE, you assign a value to rs twice.
your sql statement should contain exactly three question marks, try
select count(*) from dancers where ts between ? and ? and id = ?
next call preparedStmt.setString() three times to supply values t1, t2 and id.
Also, remember to close the connection object in the finally block.

Pull string from sql to java

I am trying to pull a first name and last name from a table in my SQL database. The queries work fine in SQL without the "as First" part and I know the db connection is fine since it works in every other part of the code.
The error I receive is that table "First" does not exist, but it should be looking at firstName and lastName for the table names, not First and Last.
Its inside of a for loop with "i", but those values are correct, playerid = i exists.
try {
String query2 = " SELECT firstName as First from player "
+ "WHERE playerid = ?";
PreparedStatement st2 = db.conn.prepareStatement(query);
st2.setInt(1, i);
ResultSet rs2 = st2.executeQuery();
if (rs2.next()) {
setFirstName(rs2.getString("First"));
}
String query3 = " SELECT lastName as Last from player "
+ "WHERE playerid = ?";
PreparedStatement st3 = db.conn.prepareStatement(query);
st3.setInt(1, i);
ResultSet rs3 = st3.executeQuery();
if (rs3.next()) {
setLastName(rs3.getString("Last"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
Change your code into something like this:
PreparedStatement ps = null;
try {
ps = db.conn.prepareStatement("SELECT firstName, lastName from player "
+ "WHERE playerid = ?");
for (int i = 0; i < MAX_PLAYERS /*<- or what is the loop condition?*/; i++) {
ps.setInt(1, i);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// should these methods really be called within a loop?
setFirstName(rs.getString("firstName"));
setLastName(rs.getString("lastName"));
}
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
ps.close();
}
}
Some considerations:
When you're using a PreparedStatement within a loop, you should create the statement once, outside of the loop and then only re-assign the bind variable(s) during each iteration.
You should minimize the number of queries you run against the DB; in your case you should select both the first and last name column in a single query.
It is important to close the resources you open up (the PreparedStatement in this case). My example shows how this is usually done (in the finally block) pre Java 7. Use the try-with-resources statement if you're using a newer Java version.

How to create and execute an SQL update statement

I have a table inside consist of variable like Username, ContactNo, Date, Name.
And i would like to do a update for Username and ContactNo only to the original record in the database.
How can i make use of update sql statement to do it?
Below is my SELECT sql statement.
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","mysql");
ps = con.createStatement();
SQL_Str="Select username,numberOfBid from customer where username like ('" + UName +"')";
//SQL_Str="Select * from customer";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString("username").toString();
dbbid=rs.getInt("numberOfBid");
//UName2 = rs.getString("username").toString();
UName2 = username;
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}
http://dev.mysql.com/doc/refman/5.0/en/update.html
And please study...
Here is a quick and dirty solution: when you have modified your values, just add something like this
String updSQL = "udate table set numberOfBid = " + dbbid + " where user = " + UName;
ps.executeUpdate(updSQL);
There are however 1000 improvements you can make such using prepared statementsand placeholders:
String updSQL = "udate table set numberOfBid = ? where username like ?";
PreparedStatement pstmt = con.prepareStatement(updSQL);
pstmt.setInt(0, dbbid);
pstmt.setString(1, UName);
pstmt.execute();
May I suggest you to have a look at Hibernate, Spring JDBC, JPA... which are on a much higher level than JDBC is.

Categories