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.
Related
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));
How to get the outcome of the query-- the AVG(DIST).
MySQL is showing this result under the column "AVG(DIST)"-- no other clue.
How do i read this value from the ResultSet instance (rs in below code)?
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
ResultSet seems to be referring to them all by column names.
Not well-familiar to JDBC -- yet!
TIA.
You can use an alias name in the query and retrieve the value in any of the two ways.!
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) AS AVERAGE_ALIAS FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
// OR
avg= rs.getDouble("AVERAGE_ALIAS");
}
Here it is:
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
}
Use alias if you have many aggregate functions in your query. See below answer!
PreparedStatement used for inserting of data,
i think you should use Statement.
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT AVG(DIST) FROM POOL_TABLE");
if( rs.next() ){
System.out.print( rs.getString(1) );
}
i hope this example would help you :)
I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}
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.
I am trying to get a count from a particular table in my derby database, but when I run the code I keep getting Invalid operation at current cursor position
public int getNumUsers(){
ResultSet rs = null;
int size = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from USERS");
while(rs.next()){
size = rs.getInt("COUNT");
}
stmt.close();
} catch (SQLException sqe) {
sqe.printStackTrace();
}
return size;
}
Change your query to
select count(*) As COUNT from USERS
or change your function call to
rs.getInt(1);
give an alias to count(*) in your select statement. in mysql we use as to give alias name.I dunno about derby though, but think it'd be similar.
rs = stmt.executeQuery("select count(*) as count from USERS");
while(rs.next()){
size = rs.getInt("count");
}