How I can count how many times a value appear in a table using jdbc? I have 200 possible values and 4 columns for records in the table.
May be by
Select count(*) from table where item = 'value';
If you want count for all 200 values then you can try:
select item,count(*) from table group by item;
Demo code:--
try {
java.sql.Statement s = conn.createStatement();
java.sql.ResultSet r = s.executeQuery("select item,count(*) from table group by item;");
while (r.next()) {
System.out.println(r.getString(1) + " "
+ r.getString(2));
}
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
Related
How can an SQL query return data from multiple tables?
for ex. my sql query suppose to list all students in specific classroom
but instead it shows only 1 student. Can this be done by system output?
if (forms.Validation.textNotEmpty(tfId)) {
try {
ResultSet rs = hogDB.getData("select * from student where sleepRoom = ("+tId.getText()+");");
if (rs.next()) {
tfStudentId1.setText(rs.getString("student_id"));
tfForNamne1.setText(rs.getString("fornamne"));
tfAfterNamne1.setText(rs.getString("AfterNamn"));
tfSleep1.setText(rs.getString("sleepRoom"));
}
} catch(Exception e) {
e.printStackTrace();
}
}
To find out whether you are really retrieving just one student or several, here’s a suggestion for a piece of test code.
try {
ResultSet rs = hogDB.getData("select * from student where sleepRoom = ("
+ tId.getText() + ");");
int count = 0;
while (rs.next()) {
System.out.format("%-10s%-20s%-20s%-8s%n",
rs.getString("student_id"), rs.getString("fornamne"),
rs.getString("AfterNamn"), rs.getString("sleepRoom"));
count++;
}
System.out.println("" + count + " students retrieved");
} catch(Exception e) {
e.printStackTrace();
}
Another possible issue, is tId.getText() a number? If it isn’t, you should probably enclose it in single quotes in the query. In any case, the recommended way is to pass a value to the database is through a ? placeholder and some setXx() call on the prepared statement.
its duplicate question with Get last inserted auto increment id in mysql
I'm creating a group it insert on M_GROUPS.
M_GROUPS table:
GROUP_ID INT AUTO_INCREMENT,
GROUP_CREATOR_ID INT
which from session.
I need to take GROUP_ID and GROUP_CREATOR_ID and insert it on
M_GROUP_MEMBERS table as
GROUP_ID INT,
MEMBER_ID INT.
My problem is I can't take auto increment value GROUP_ID from M_GROUPS
public void groupCreation(String groupname, int grouptype, int creator_id) {
DatabaseService oDatabaseService = new DatabaseService();
Connection connection = oDatabaseService.connect();
try {
Statement stmt = null;
stmt = connection.createStatement();
String sql;
sql = "INSERT INTO M_GROUPS( GROUP_NAME, GROUP_CREATOR_ID,
GROUP_TYPE, CREATION_TIME)"
+ " VALUES ('"
+ groupname
+ "','"
+ creator_id
+ "','"
+ grouptype + "',NOW())";
//stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Use getGeneratedKeys() method from your Statement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.
Change:
stmt.executeUpdate(sql);
To:
int rowsAffected =
stmt.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS );
ResultSet rs = stmt.getGeneratedKeys();
//******************************************************
// in case of batch insert, you can check how many are inserted
rs.last();
int rows = rs.getRow();
System.out.println( "Generated keys count: " + rows );
//******************************************************/
int currentRow = 1;
rs.beforeFirst();
while( rs.next() ) {
System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );
} // while rs
Once you have this auto generated key value in a variable, you can use it with other SQL statements, to store in other tables.
Note: Call to getGeneratedKeys() may throw java.sql.SQLFeatureNotSupportedException, if the JDBC driver, that you are using, does not support this method.
I want to fetch last value in a column in a row in a derby db table. Can someone help me?
SELECT *
FROM dbo.rawImport
WHERE number= ( select max(number)
from dbo.rawImport)
Try this one if you are trying to get last id (numeric value)
SELECT MAX(COLUMN_NAME)
FROM TABLE_NAME
thats it.
And if you want to get whole data of last row then call getRowCount() method and select the record at that reference. check out code example.
getRowCount() method:
public int getRowCount(String tableName) {
int count = 0;
try {
res = st.executeQuery("SELECT COUNT(*) FROM " + tableName);
while (res.next()) {
count = res.getInt(1);
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Table not found record getting");
}
return count;
}
It will return an int value so use it as
SELECT * FROM TABLE_NAME WHERE ID = getRowCount(TABLE_NAME);
And the result is your last record.
I'm not getting data into mysql
void connectionDB() {
try {
Class.forName(fileReader.getdriver());
String url = "jdbc:mysql://"+ fileReader.gethost() + ":" + fileReader.getDBport() +"/" + fileReader.getdbname();
conn = DriverManager.getConnection(url, fileReader.getusername(),fileReader.getpasswd());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
}
}
public void snmp_mysql(String ipv6Address, String[] resString) {
try {
stat = conn.createStatement();
String sql =
("INSERT INTO Statistics3 VALUES ('" + ipv6Address + "','"
+ dateTime.trim() + "'," + battpercent + ")");
stat.executeUpdate(sql);
stat.close();
System.out.println("updating");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQL statement is not executed!");
}
}
The code is not showing any error and it is showing Empty set (0.01 sec) in MySQL. Previously it worked properly and got the output. I didn't make any changes. I do not know why its not working.
I have taken another class in another project and added some columns to the existing table Statistics3,and used mysql for that class.I didnt make any changes in this class.That doesn't effect mysql know
While i'm running the project,i'm getting these errors in the middle of the output
java.sql.SQLException: Column count doesn't match value count at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
You can explicitly specify the column into which you want to insert data.. As you can see, you can also skip some column..
String sql =
"INSERT INTO Statistics3 (column1, column2, column4) VALUES ('" + ipv6Address
+ "','" + dateTime.trim() + "'," + battpercent + ")";
column1, column2, and column4 are columns corresponding to your values - ipv6Address, datetime, and battpercent.. in your table..
So, if you have inserted a column - column3 , then you can just skip it.. It will get the default value as you have set..
added some columns to the existing table Statistics3
There is your problem. Number of values does not match with number of columns present.
You should use version of SQL statement
insert into table (col1,col2) values (val1,val2)
The values given in the insert query doesn't match with the columns in the DB. Make sure that you have values for all the columns(in your table) in your query.
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