I am using CsvJdbc (it is a JDBC-driver for csv-files) to access a csv-file. I don't know how many columns the csv-file contains. How can I get the number of columns? Is there any JDBC-function for this? I can not find any methods for this in java.sql.ResultSet.
For accessing the file, I use code similar to the example on the CsvJdbc website.
You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
Number of a columns in the result set you can get with code (as DB is used PostgreSQL):
//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);
//create statement
Statement stat = conn.createStatement();
//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");
//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();
//columns count from metadata object
int numOfCols = rsmd.getColumnCount();
But you can get more meta-informations about columns:
for(int i = 1; i <= numOfCols; i++)
{
System.out.println(rsmd.getColumnName(i));
}
And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.
After establising the connection and executing the query try this:
ResultSet resultSet;
int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("column count : "+columnCount);
This will print the data in columns and comes to new line once last column is reached.
ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
if(!(i==columnCount)){
System.out.print(res.getString(i)+"\t");
}
else{
System.out.println(res.getString(i));
}
}
Related
I need to verify if a column already exists in a table . My class extends CustomTaskChange so my method receives a Database object as an argument. Can I make the verification I want trough the ResultSetObject?
#Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
DatabaseMetaData metadata;
metadata = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = metadata.getTables(null, null, "%", types);
Statement s = connection.createStatement();
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.suffix)) {
String sql = sqlStatement.replaceAll("name", tableName);
s.execute(sql);
}
}
}
Basically what this piece of code is doing is going through all the tables in my database. If, a table name ends in a suffix, I will add the column to it. This way I can add a column to multiple tables at the same time.
But I want to add another verification to add the column to a table, and that is that there can't already be a column with that name in that table. Something like this(pseudocode)
if(tableName.endsWith(this.suffis) && columnName doesn't exist in that table){
String sql = sqlStatement.replaceAll("name", tableName);
s.execute(sql);
}
you can fetch columns from each of the tables then you can check column exist or not.
{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM TABLENAME LIMIT 1");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
if(col_name.equals("YourColumnName"){
/*Then the column already exist*/
}}
With the above code, you can check the metadata and then execute the SQL query to delete the same.
I have a basic java application and a sqlite DB.
I can create table manually through sqLite browser. And I am able to access these tables from my JAVA application.
E.g. Reading from existing table: (I have omitted the try catch blocks in the sample below just to reduce the length of question)
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "select * from test1 where uname = ? and name = user1";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "test");
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
return true;
else
return false;
I am able to perform this query successfully.
However, if I create / modify a table, changes does not show up in SQlite DB (I am viewing db in sqLite browser). If I copy paste the same query in SQlite browser, the query runs successfully and a row is added.
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "INSERT INTO COMPANY (ID,NAME,AGE) VALUES (3, 'tOM', 32);";
preparedStatement = connection.prepareStatement(query);
preparedStatement.executeUpdate();
Am I missing something?
EDIT: Both the above tables exist in my sqlite db. Both were created through sqlite browser
EDIT2: I was getting true from my example 1 above, that's why I felt that I am able to read from db. I update my code to print the data read and nothing gets printed which means I am not able to read the data as well:
resultSet = preparedStatement.executeQuery("SELECT * FROM test1");
and
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
The connection string is:
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\akshay\\sqlite_test.sqlite");
conn.setAutoCommit(true);
return conn;
I've learned some MySQL recently and now I'm trying to work with a database in Java.
Today I've faced a problem of retrieving data from the whole column.
I already know, that if i do like:
ResultSet res = st.executeQuery("SELECT * FROM table_name WHERE id = n");
I get the whole raw. And then using
ResultSetMetaData metadata = res.getMetaData();
int colCount = metadata.getColumnCount();
while (res.next()) {
for (int i = 1; i <= colCount; i++){
String colValue = res.getString(i);
System.out.println(colValue);
}
}
I can sysout all values of the columns of this raw.
Now I have this
ResultSet res = st.executeQuery("SELECT column_name FROM table_name");
So I get one column and I need to iterate through it and sysout all the values.
Thanks in advance! :)
You can do
while (res.next()) {
String colValue = res.getString("column_name");
System.out.println(colValue);
}
And it will grab the String value from that row of the result set.
You can directly try, if you don't know the column count then use
ResultSetMetaData metadata = res.getMetaData();
So just execute like
ResultSet res = st.executeQuery("SELECT column_name FROM table_name");
while (res.next()) {
String colValue = res.getString(1);
//-------------OR--------------
String colValue2 = res.getString("column_name");
System.out.println(colValue);
System.out.println(colValue2);
}
I have a sql query fro which I need the column name and data type and it's table name and schema name:
Thsi is the method I am using for using and testing it for SQLSERVER:
public static void getMetadataForConn(Connection conn) throws SQLException
{
ResultSet rs = null;
try
{
Statement stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT AB_DEMO_SRC.dbo.employee.dept_id dept_id, AB_DEMO_SRC.dbo.employee.email_add email_add, AB_DEMO_SRC.dbo.employee.emp_address emp_address, AB_DEMO_SRC.dbo.employee.emp_id emp_id, AB_DEMO_SRC.dbo.employee.emp_name emp_name FROM AB_DEMO_SRC.dbo.employee ");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++)
System.out.print(md.getColumnName(i) + "(" + md.getColumnType(i) + ") "+md.getSchemaName(i)+"."+md.getTableName(i));
System.out.println();
while (rs.next())
{
for (int i = 1; i <= columnCount; i++)
{
Object o = rs.getObject(i);
System.out.print(null == o ? "" : o.toString() + " ");
}
System.out.println();
}
}
finally
{
if (null != rs)
{
rs.close();
}
}
}
I get all the other metadata details like data type, precision and scale..Strangely, I am getting tablename and schema name as "" that is blank..IS there any other way to fetch the metadata of the columns present in a Query?
I think the problem is that the columns of a ResultSet are not related to any table, they are related just to the query. The query could be complex, it could have computed columns etc. That is why their table names are blank.
If you want to get the information about the columns of a specific table, you can use the metadata of the database:
DatabaseMetaData meta = conn.getMetaData();
ResultSet columns = meta.getColumns(null, "dbo", "employee", null);
You can fetch column name by calling 'getMetaData' method of ResultSet.
ResultSetMetaData metaData= resultSet.getMetaData();
String columnName = metaData.getColumnName(1);
All other column meta data can also be fetching using object of ResultSetMetaData
Can anyone tell me how I can compare two resultset values? Only getting error in if statement, but the rest is working.
Statement s = con.createStatement();
Statement stmnt = con.createStatement();
String query = "select * from tbl_product";
s.execute(query);
ResultSet rs = s.getResultSet();
while(rs.next())
{
String strOuter=rs.getString(2);
System.out.println(strOuter);
String query1 = "select * from PRODUCTS_AJ";
stmnt.execute(query1);
ResultSet rs1 = stmnt.getResultSet();
while(rs1.next())
{
System.out.println("-------"+rs1.getString(2));
if(rs.getString(2).equals(rs1.getString(2)))// Getting Error here for this line
{
System.out.println("Found");
}
}
}
java.sql.Exception data not found
This types of error occurs when you try to read same column of the same cursor multiple times. And what you encountered is a typical scenario. Just store the string temporarily like bellow:
String col3 = rs1.getString(2);
and use col3 instead of rs1.getString(2), whenever needed.
System.out.println("-------"+ col3);
if(col3.equals(rs1.getString(2)))
{
...
You cannot re-read a column value again. So, copy it in a local variable for logging.
String val = rs1.getString(2);
System.out.println("-------" + val);
if (rs.getString(2).equals(val)) {
What you could possibly do is
use SQL where clause
String query1 = "select * from PRODUCTS_AJ where fieldNmae = 'something'";
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
if (colCount > 1)
{
// found
}
For ResultSetMetaData
or possibly do
ResultSet rsOLD = null;
ResultSet rs = s.getResultSet();
// rs will be new ResultSet
while(condition)
{
// check from second row (maintain if case)
.
.
.
// end of loop
rsOLD = rs;
}
Ok ! This is a typical error while using JDBC-ODBC bridge driver with MS Access. I have experienced.I solved it in following way. Retrieving the same data more than once from the result set.
Please try like this
ResultSet rs = s.getResultSet();
String str=rs.getString(2);
Use this string to compare
str.equals(rs2.getString(2)
Thanks!
rs.getSting(2) is executed the number of row times of rs1 in the while loop of rs1. You may not have the that many number of rows in rs as rs1.