I know that I can count the entries in SQL with
SELECT COUNT (*) FROM table
but I don't know how do perfom that in Java.
This is my Code to perform a SQL command.
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT COUNT (*) FROM table")
Result:
rs2: org.h2.result.LocalResult#41cf3f60 columns: 1 rows: 1 pos: -1
But it should return > 20
My code:
Connection conn = null;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection(
"jdbc:h2:" + Environment.getExternalStorageDirectory()
+ "/sorter/database", "", "");
Statement stmt = conn.createStatement();
Toast.makeText(context,
String.valueOf(stmt.executeQuery(sql)),
Toast.LENGTH_LONG).show();
conn.close();
if (conn != null)
conn.close();
What you see is the toString() method of the ResultSet you never actually retrieve a value from the result.
executeQuery returns a ResultSet that you use to get the actual data. It is not the result of the query directly (think about how this should work when returning multiple rows and multiple columns)
You need to do something like this:
ResultSet rs = stmt.executeQuery(sql);
int count = -1;
if (rs.next())
{
count = rs.getInt(1);
}
This is all nicely explained in the JDBC Tutorial:
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/resultset.html#998035
Another possibility is
ResultSet rs=conn.prepareStatement("SELECT COUNT(*) FROM table").executeQuery();
if(rs.next()) sysout(rs.getInt(1));
Related
I am using Java 8 and oracle.
I have confirmed that this code is working:
Statement stmt = null;
String query = "select * from custref";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
When I change it to this, it does not give any results:
PreparedStatement prepStmt = null;
String query = "select * from custref where CUSTOMER_NUMBER = ?";
prepStmt = con.prepareStatement(query);
prepStmt.setString(1, "12344321");
ResultSet rs = prepStmt.executeQuery();
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
I have confirmed that my data type is VARCHAR hence the set string. I know my connections are fine because the basic search works just when I switch to parameterized it doesn't fail or throw exceptions it just doesn't have a result set. I have also tried the :customerNumber convention instead of the ? and this didn't work either. This is quite embarrassing but I am at my end here, nothing I can find seems to address this.
I want to show the Column numbers of a table but it always shows the number 1. I have written the code below:
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql;
sql = "SELECT count(*) FROM information_schema.columns WHERE
table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql)) {
int columCount = rs.getMetaData().getColumnCount();
System.out.println("Column number is: "+columCount);
}
stmt.close();
con.close();
Where is the error ?
First, you haven't needed Class.forName to load your JDBC drivers in a long time. Second, you are selecting a value but you are reading metadata. Third, when using try-with-resources you don't need explicit close calls (and your Connection should be closed in a finally, for example). Finally, use PreparedStatement and bind parameters. Like,
java.sql.Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "SELECT count(*) FROM information_schema.columns WHERE table_name=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, "my_b");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
} else {
System.out.println("No rows");
}
}
} finally {
con.close();
}
You are not retrieving the result of the query, instead you are asking the result set metadata how many columns the result set has. And as your query only produce a single column (ie COUNT(*)), the result of ResultSetMetaData.getColumnCount() is 1, and that value is correct.
If you want to get the result of the query, you need to get it from the result set:
try (ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
int columnsNumber = rs.getInt(1);
System.out.println("Column number is: "+columnsNumber );
}
}
The problem is that ResultSet.getColumnCount returns the number of columns in the query's result set, not the number of columns in a table.
If you are trying to get a count of columns on a table, the query you have is correct. You just need to retrieve the result of the query, rather than its metadata.
String sql = "SELECT count(*) FROM information_schema.columns WHERE table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql));
rs.next();
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
}
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'database_name' AND table_name = 'table_name'"
try (
ResultSet rs = stmt.executeQuery(sql)) {
//int columCount = rs.getMetaData().getColumnCount();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
System.out.println("Column number is: "+columnsNumber );
}
stmt.close();
con.close();
Try SELECT * FROM information_schema.columns WHERE table_name=\"my_b\"
Just omit the count(*) since this returns a single result, while you are looking for all columns.
I'm trying to send in ORDER table last ID from CUSTOMER and all IDs from PRODUCT tables. In "idproduct"(ORDER table) should appears all IDs with white spaces between them. I used here rs.next() twice and I know that it isthe reason why error appears, but how can I handle it? Here is a code:
List<String> IDproducts = new ArrayList<>();
Connection conn = db.getConnect();
PreparedStatement pst = conn.prepareStatement("SELECT * FROM `onlineshop`.`customer`");
ResultSet rs = pst.executeQuery();
while (rs.next()){
rs.getString(1);
}
Connection conn1 = db.getConnect();
PreparedStatement pst1 = conn1.prepareStatement("SELECT * FROM `onlineshop`.`product`");
ResultSet rs1 = pst1.executeQuery();
while (rs1.next()){
IDproducts.add(rs1.getString(1));
}
db.Query("INSERT INTO `onlineshop`.`order` (`idcustomer`, `idproduct`)
VALUES ('"+rs.getString(1)+"','" + IDproducts + ")");
error:
java.sql.SQLException: After end of result set
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
i have the below code, where I'm inserting records to a table. When I try to get resultset, it returns null. How to get the latest added row into a resultset?
String sql1 = "INSERT INTO [xxxx].[dbo].[xxxxxx](WORKFLOW_SEQ_NBR," +
" WORKFLOW_LOG_TYPE_CODE, WORKFLOW_STATUS_CODE, DISP_CODE, DISP_USER, DISP_COMMENT, DISP_TITLE, DISP_TS)" +
"VALUES(?,?,?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(sql1);
pst.setString(1, ...);
pst.setString(2, ...);
...
...
...
pst.executeUpdate();
ResultSet rstest = pst.executeQuery();
// ResultSet rstest = pst.getResultSet();
EDIT: Resolved
added following method to go to the last added row
st.execute("Select * from [xxxx].[dbo].[xxxxxxxxx]");
ResultSet rstest = st.getResultSet();
rstest.afterLast();
GETLASTINSERTED:
while(rstest.previous()){
System.out.println(rstest.getObject(1));
break GETLASTINSERTED;//to read only the last row
}
When using a SQL statement such as INSERT, UPDATE or DELETE with a PreparedStatement, you must use executeUpdate, which will return the number of affeted rows. In this case there is simply no ResultSet produced by the sql operation and thus calling executeQuery will throw a SQLException.
If you actually need a ResultSet you must make another statement with a SELECT SQL operation.
See the javadoc for PreparedStatement#executeQuery and PreparedStatement#executeUpdate
Seems like this is an older question, but i'm looking for a similar solution, so maybe people will still need this.
If you're doing an insert statement, you can use the :
Connection.PreparedStatement(String, String[]) constructor, and assign those to a ResultSet with ps.getGeneratedKeys().
It would look something like this:
public void sqlQuery() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection conn; //Assume this is a properly defined Connection
String sql = "insert whatever into whatever";
ps = conn.prepareStatement(sql, new String[]{"example"});
//do anything else you need to do with the preparedStatement
ps.execute;
rs = ps.getGeneratedKeys();
while(rs.next()){
//do whatever is needed with the ResultSet
}
ps.close();
rs.close();
}
Connection#prepareStatement() - Creates a PreparedStatement object for sending parameterized SQL statements to the database.
which means connect.prepareStatement(sql1); created the PreparedStatement object using your insert query.
and when you did pst.executeUpdate(); it will return the row count for SQL Data Manipulation Language (DML) statements or 0 for SQL statements that return nothing
Now if you again want to fetch the data inserted you need to create a new PreparedStatement object with Select query.
PreparedStatement pstmt = connect.prepareStatement("SELECT * FROM tableName");
then this shall give you the ResultSet object that contains the data produced by the query
ResultSet rstest = pstmt.executeQuery();
Im trying to make a dynamic Delete Query.
What im basically trying to do is first grab the name of the first column in any table (the primary key). Then i use that in Another Query to delete from that table though i get a nullpointerexception?
Ohh and the primary key is not an INT like 1,2,3,4,5 etc.. it's formed up as S1,S2,S3,S4,S5 etc and has the type TEXT.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+tablename+" WHERE " +FirstColumn+ " = " +row;
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
I am going to assume that all the variables you are using have been initialized.
I added single quotes around the FirstColumn name.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+ tablename +" WHERE " + FirstColumn + " = '" + row + "'";
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
If you are still getting an error you should try printing out your row name and see what it prints out.
Edit: Since you are new stylistically it's preferable to add a single space when using operators to improve code readability. For example 1+3+x+34 is a lot harder to read than 1 + 3 + x + 34. Granted there is no "wrong" code style but improving code readability is always a plus.
Initialize your stmt object...
stmt = c.createStatement();
before executing the query.