Exporting from oracle database to csv file - java

import java.io.*;
import java.sql.*;
public class CsvF {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","sandp");
conn.setAutoCommit(false);
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from tet where to_char(S_DATE,'HH24') = '23'");
ResultSetMetaData rsmd = rs.getMetaData();
FileWriter cname = new FileWriter("D:\\asd.csv");
BufferedWriter bwOutFile = new BufferedWriter(cname);
StringBuffer sbOutput = new StringBuffer();
sbOutput.append("S_DATE");
bwOutFile.append(sbOutput);
bwOutFile.append(System.getProperty("line.separator"));
System.out.println("No of columns in the table:"+ rsmd.getColumnCount());
for (int i = 1; i <= rsmd.getColumnCount(); i++)
{
String fname = rsmd.getColumnName(i);
}
System.out.println();
while(rs.next())
{
System.out.print(rs.getString(1));
bwOutFile.append(rs.getString(1));
bwOutFile.append(System.getProperty("line.separator"));
bwOutFile.flush();
System.out.println();
}
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
System.out.println("Unable to connect to database" +e);
}
}
}
here i am getting data into asd.csv file as follows=
2015-2-26.23.21. 0. 0
2015-2-26.23.43. 0. 0
2015-2-27.23.28. 0. 0
2015-2-27.23.50. 0. 0
2015-3-1.23.19. 0. 0
2015-3-1.23.41. 0. 0
but i want to get data as following format =
2015-02-26 23:21
2015-02-26 23:43
2015-02-27 23:28
2015-02-27 23:50
2015-03-01 23:19
2015-03-01 23:41
i am getting an extra dot(".") in the output... what i am doing wrong?
i have create a table named tet with coloumn(S_DATE) where S_DATE is timestamp...can anyone help me?

Use rs.getTimestamp() instead of rs.getString() and convert your timestamp to string using SimpleDateFormat.
TimeStamp ts= rs.getTimeStamp(1);
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd hh:mm");
String yourFormatedDate = formater.format(ts);

Related

No buffer space available, maximum connection reached

package Simple;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.text.*;
public class CurrentProg {
//connecting to the database
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION ="jdbc:mysql://localhost:3306/db?autoReconnect=true";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
static Connection dbConnection = null;
static Statement statement = null;
static int total=1;
//Searching between startdate and enddate
public static java.util.LinkedList searchBetweenDates(java.util.Date startDate, java.util.Date endDate) {
java.util.Date begin = new Date(startDate.getTime());
java.util.LinkedList list = new java.util.LinkedList();
list.add(new Date(begin.getTime()));
java.util.Date end = new Date(endDate.getTime());
endDate.setTime(endDate.getTime() + 24*3600*1000);
Calendar cal = Calendar.getInstance();
cal.setTime(begin);
dbConnection = getDBConnection();
while(begin.compareTo(endDate)<0){
begin = new Date(begin.getTime() + 86400000);
list.add(new Date(begin.getTime()));
Timestamp timestamp = new Timestamp(new Date().getTime());
//For a single day calculation: 24hours*60mins=1440 /2 (2 mins time difference as per the requirement) = 720
for (int j = 0; j < 720; j++) {
cal.add(Calendar.MINUTE, 2);
timestamp = new Timestamp(cal.getTime().getTime());
String S = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
String[] parts = S.split(" ");
String date=parts[0];
String time=parts[1];
cal.getTime().toString();
// To create data loop into a List
List<String> records = new ArrayList<String>();
StringBuffer record = new StringBuffer();
for (int i = 1; i <= total; i++) {
records = new ArrayList<String>(total);
int a2 = 220 + j % 31; // 230 - 244 by 1
String wString = Integer.toString(a2);
String a = String.valueOf(a2);
double b2 = 0.00 + j % 3.7 ; // 1.3 - 3.9 by 0.1
String aString = Double.toString(b2);
String b = String.valueOf(b2);
b = b.substring(0, Math.min(b.length(), 5));
record.delete(0, record.length());
record.append(a + "," + b + ",'"+ date + "', '"+ time + "'");
record.append("\t\t");
record.append("\n");
records.add(record.toString());
//Insert Query
String insertTableSQL = "INSERT INTO cmd1"
+ "(a, b, date, time) " + "VALUES"
+ "("+record.toString()+")";
System.out.println("insertTableSQL - " + insertTableSQL); // Statement.executeUpdate(insertTableSQL);
try {
statement = dbConnection.createStatement();
statement.executeUpdate(insertTableSQL);
System.out.println("Record is inserted into Db table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
// dbConnection = getDBConnection();
statement = dbConnection.createStatement();
statement.executeUpdate(insertTableSQL);
System.out.println("Record is inserted into Db table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
// httpPost.releaseConnection()
try{
if(statement!=null)
statement.close();
}
finally{
}
try{
if(dbConnection!=null)
dbConnection.close();
}
finally{
}
}
}
}
}
return list;
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
//To enter startDate and enddate
// EntityManagerFactory.getCache().evictAll;
SimpleDateFormat startDate=new java.text.SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat endDate=new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.LinkedList hitList = searchBetweenDates(
startDate.parse("2016-01-01"),
endDate.parse("2016-03-01"));
String[] combo = new String[hitList.size()];
for(int i=0; i<hitList.size(); i++)
combo[i] = new java.text.SimpleDateFormat("yyyy-MM-dd").format(((java.util.Date)hitList.get(i)));
}
private static void insertRecordIntodb() {
//
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
Server connection failure during transaction. Due to underlying exception: 'java.net.SocketException: java.net.SocketException: No buffer space available (maximum connections reached?): connect'.
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.SocketException: No buffer space available (maximum connections reached?): connect
STACKTRACE:
java.net.SocketException: java.net.SocketException: No buffer space available (maximum connections reached?): connect
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2717)
at com.mysql.jdbc.Connection.<init>(Connection.java:1509)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Simple.CurrentProg.getDBConnection(CurrentProg.java:186)
at Simple.CurrentProg.searchBetweenDates(CurrentProg.java:126)
at Simple.CurrentProg.main(CurrentProg.java:164)
** END NESTED EXCEPTION **
Attempted reconnect 3 times. Giving up.
Exception in thread "main" java.lang.NullPointerException
at Simple.CurrentProg.searchBetweenDates(CurrentProg.java:137)
at Simple.CurrentProg.main(CurrentProg.java:164)
Here I am trying to connect java program with database but when i am trying to insert large data say for 1 month so its only fetching 16000 records not more than that i want the data should be inserted as per the given date range what should i do to get that . In stacktrace its showing an exception as no buffer space available maximum connection reached. Thanks In advance
Here is the modified code. I removed a lot of code which is not necessary:
public static LinkedList<Date> searchBetweenDates(Date startDate, Date endDate) throws SQLException {
Date begin = new Date(startDate.getTime());
LinkedList<Date> list = new LinkedList<Date>();
list.add(new Date(begin.getTime()));
endDate.setTime(endDate.getTime() + 24 * 3600 * 1000);
Calendar cal = Calendar.getInstance();
cal.setTime(begin);
dbConnection = getDBConnection();
PreparedStatement ps = dbConnection.prepareStatement("INSERT INTO cmd1(aaaa, bbbb, datee, timee) VALUES(?, ?, ?, ?)");
while (begin.compareTo(endDate) < 0) {
begin = new Date(begin.getTime() + 86400000);
list.add(new Date(begin.getTime()));
Timestamp timestamp = new Timestamp(new Date().getTime());
// For a single day calculation: 24hours*60mins=1440 /2 (2 mins time
// difference as per the requirement) = 720
for (int j = 0; j < 720; j++) {
cal.add(Calendar.MINUTE, 2);
timestamp = new Timestamp(cal.getTime().getTime());
String S = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
String[] parts = S.split(" ");
String date = parts[0];
String time = parts[1];
cal.getTime().toString();
// To create data loop into a List
for (int i = 1; i <= total; i++) {
int a2 = 220 + j % 31; // 230 - 244 by 1
String a = String.valueOf(a2);
double b2 = 0.00 + j % 3.7; // 1.3 - 3.9 by 0.1
String b = String.valueOf(b2);
b = b.substring(0, Math.min(b.length(), 5));
ps.setString(1, a);
ps.setString(2, b);
ps.setString(3, date);
ps.setString(4, time);
ps.execute();
}
}
}
if (ps != null)
ps.close();
if (dbConnection != null)
dbConnection.close();
return list;
}
What I changed:
I removed your try/catch's because I wanted to make the code short so that I can edit it here easily. But you should handle exception correctly. And don't swallow exceptions ever. I mean the following is no go:
} catch (SQLException e) {
System.out.println(e.getMessage());
}
It is very bad Idea because you'll not see the real cause of the problem in this case; at least do e.printStackTrace() eventhough it is not recommended in a real project.
I exchanged the Statement object for PreparedStatement because it is much more efficient.
Removed package names and put import statements instead because it is not necessary to do so unless you have different classes from different packages with the same name.
I changed column names because my DB does not want to accept them. Column names like a are very bad. Choose instead descriptive names so that you might understand what it is for a couple of months later. Don't use column names like date because they are reserved words for some databases systems I know.
Don't create database resources like Connection in a loop unless it is absolutely needed! Otherwise, your program will go out of resources because these resources are very expensive! That is exactly what you are experiencing right now.
Hope it helps, otherwise, drop me a comment.

How to store sql resultset fields in to a separate array variable using java?

I have three fields of a table orderinfo ,having around 2500 rows in my database.
Now I want to store each and every field data in a array variable.
when i run the code, I am getting Null values stored on the array variable.
Below I have provided my code.
Can any one help me to achieve this?
Thanks in advance.
package com;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException;
public class getOrderinfo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.10.10.14/opsbank-ii";
static final String USER = "root";
static final String PASS = "p#ssw0rd";
public static int row_count = 0;
public static int count_for_totalfiles = 0;
public static String filename_allocated = "";
public static String dateofcar_allocated = "";
public String row_data = "";
public static int orderid = 0;
public static int[] orderid_sto = new int[5000];
public static String flow = "";
public static String[] flow_sto = new String[5000];
public static Date dateofprocessing;
public static Date[] dateofprocessing_sto = new Date[5000];
public static void main(String args[]) {
//public static void main(String[] args)
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date(Format : 2016-02-22) ");
String date = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2 = null;
/* try {
//Parsing the String
date2 = (Date) dateFormat.parse(date);
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("Input Date:" + date2);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "select orderid,flow,dateofprocessing from orderinfo where ordertype ='CAR' and dateofprocessing like '%" + date + "%'";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
int i = 0;
orderid = rs.getInt("orderid");
System.out.println("Order ID get : " + orderid);
orderid_sto[i++] = orderid;
flow = rs.getString("flow");
flow_sto[i++] = flow;
dateofprocessing = rs.getDate("dateofprocessing");
dateofprocessing_sto[i++] = dateofprocessing;
System.out.println("orderid :" + orderid + " || Flow : " + flow + " || date : " + dateofprocessing);
i++;
row_count++;
count_for_totalfiles++;
//Display values
//System.out.print("BOOKISSID: " + BOOKISSID);
//System.out.print(", ISSN: " + ISSN);
//System.out.println("\n");
}
System.out.println("Total Number of CAR orders found for the date : " + date2 + " = " + row_count);
System.out.println("The Details after calculation:\n");
for (int j = 0; j < count_for_totalfiles; j++) {
System.out.println("I am executed number : " + j);
System.out.println("orderid :" + orderid_sto[j] + " || Flow : " + flow_sto[j] + " || date: " + dateofprocessing_sto[j]);
}
// row_count=0;
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (MySQLSyntaxErrorException mysqlerr) {
System.out.println("date issue");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
}//end main
}//end FirstExample
Kindly help any one if possible.
Try to increment i once time like this:
orderid_sto[i]=rs.getInt("orderid");
flow_sto[i]=rs.getString("flow");
dateofprocessing_sto[i]=rs.getDate("dateofprocessing");
i++;
And remove these line because they are present in finally block:
//STEP 6: Clean-up environment
stmt.close();
conn.close();
You should only increment i once, you are incrmenting it multiple times
your code:
orderid_sto[i++]=orderid;
flow=rs.getString("flow");
flow_sto[i++]=flow;
dateofprocessing=rs.getDate("dateofprocessing");
dateofprocessing_sto[i++]=dateofprocessing;
i++;

java code for importing xls data into mysql database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to import xls file into mysql but getting an error of Nullpointer EXCEPTION please give me the solution
package abhi;
public class ImportData {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test","root","abhi1402");
con.setAutoCommit(false);
PreparedStatement pstm = null ;
FileInputStream input = new FileInputStream("D:/New Folder/apnakhata1.xls");
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
for(int i=1; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
String CountryName = row.getCell(1).getStringCellValue();
String CountryCode = row.getCell(2).getStringCellValue();
String BankName = row.getCell(3).getStringCellValue();
String Website = row.getCell(4).getStringCellValue();
String Name = row.getCell(5).getStringCellValue();
String SMS = row.getCell(6).getStringCellValue();
int SMSNumber = (int) row.getCell(7).getNumericCellValue();
int CustomerCare = (int) row.getCell(8).getNumericCellValue();
String sql = "INSERT INTO Bank VALUES('"+CountryName+"','"+CountryCode
+"','"+BankName+"','"+Website+"','"+Name+"','"+SMS+"','"+SMSNumber
+"','"+CustomerCare+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(SQLException ex){
System.out.println(ex);
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
}
}
Reason of NullPointerException in your code is due to
for(int i=1; i<=sheet.getLastRowNum(); i++)
Check your Excel file. It may contains some blank rows or may be some blank column values and then run your code.
you have to put
String CountryName = row.getCell(0).getStringCellValue();
String CountryCode = row.getCell(1).getStringCellValue();
String BankName = row.getCell(2).getStringCellValue();
String Website = row.getCell(3).getStringCellValue();
String Name = row.getCell(4).getStringCellValue();

connector for Pervasive [duplicate]

How can I create a connector for Pervasive PSQL in Java?
How can I create a connector for Pervasive PSQL? I created a sample connector, but I am not sure whether it is right or wrong.
Here's a simple program I have that works for me to connect to a Pervasive PSQL database:
/*
* SQLStatement.java
* Simple JDBC Sample using Pervasive JDBC driver.
*/
import java.*;
import java.sql.*;
import pervasive.jdbc.*;
import java.io.*;
public class SQLStatement {
public static void main(String args[]) {
String url = "jdbc:pervasive://localhost:1583/demodata?transport=tcp";
Connection con;
String query = "select* from class";
Statement stmt;
try {
Class.forName("com.pervasive.jdbc.v2.Driver");
} catch(Exception e) {
System.err.print("ClassNotFoundException: ");
System.out.println(e.toString());
System.err.println(e.getMessage());
}
try {
Connection conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount = 1;
long j = 0;
int i = 1;
while (rs.next()) {
System.out.println("Row " + rowCount + ": ");
for (i = 1; i <= numberOfColumns; i++) {
System.out.print(" Column " + i + ": ");
System.out.println(rs.getString(i));
}
System.out.println("");
rowCount++;
}
System.out.println("Waiting.");
String thisLine;
try {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(converter);
while ((thisLine = br.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error: " + e);
}
stmt.close();
conn.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
}
To compile it, I use:
javac -classpath "C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2.jar";"C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2x.jar";"C:\Program Files\Pervasive Software\PSQL\bin\jpscs.jar";. SQLStatement.java
And to run it, I use:
java -classpath "C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2.jar";"C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2x.jar";"C:\Program Files\Pervasive Software\PSQL\bin\jpscs.jar";.\ SQLStatement.java
You might need to change the location of the PSQL JAR files if you are using a 64-bit OS.
I use the following library with Dbeaver for querying in a Pervasive database:
jpscs.jar
pvjdbc2x.jar
pvjdbc2.jar

Retrieve column names from java.sql.ResultSet

With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.
You can get this info from the ResultSet metadata. See ResultSetMetaData
e.g.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);
and you can get the column name from there. If you do
select x as y from table
then rsmd.getColumnLabel() will get you the retrieved label name too.
In addition to the above answers, if you're working with a dynamic query and you want the column names but do not know how many columns there are, you can use the ResultSetMetaData object to get the number of columns first and then cycle through them.
Amending Brian's code:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
This question is old and so are the correct previous answers. But what I was looking for when I found this topic was something like this solution. Hopefully it helps someone.
// Loading required libraries
import java.util.*;
import java.sql.*;
public class MySQLExample {
public void run(String sql) {
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost/demo";
// Database credentials
String USER = "someuser"; // Fake of course.
String PASS = "somepass"; // This too!
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
Vector<String> columnNames = new Vector<String>();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
System.out.print(columns.getColumnName(i) + "\t");
columnNames.add(columns.getColumnName(i));
}
System.out.print("\n");
while (rs.next()) {
for (i = 0; i < columnNames.size(); i++) {
System.out.print(rs.getString(columnNames.get(i))
+ "\t");
}
System.out.print("\n");
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception mysqlEx) {
System.out.println(mysqlEx.toString());
}
}
}
}
SQLite 3
Using getMetaData();
DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);
System.out.println("your_table_name");
while (rset.next())
{
System.out.println("\t" + rset.getString(4));
}
EDIT: This works with PostgreSQL as well
import java.sql.*;
public class JdbcGetColumnNames {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/komal", "root", "root");
st = con.createStatement();
String sql = "select * from person";
rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " + metaData.getTableName(2));
System.out.println("Field \tDataType");
for (int i = 0; i < rowCount; i++) {
System.out.print(metaData.getColumnName(i + 1) + " \t");
System.out.println(metaData.getColumnTypeName(i + 1));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Table Name : person
Field DataType
id VARCHAR
cname VARCHAR
dob DATE
while (rs.next()) {
for (int j = 1; j < columncount; j++) {
System.out.println( rsd.getColumnName(j) + "::" + rs.getString(j));
}
}
When you need the column names, but do not want to grab entries:
PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");
ResultSet set = stmt.executeQuery();
//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }
NOTE: Only works with MySQL
The SQL statements that read data from a database query return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The **java.sql.ResultSet** interface represents the result set of a database query.
Get methods: used to view the data in the columns of the current row
being pointed to by the cursor.
Using MetaData of a result set to fetch the exact column count
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html
and further more to bind it to data model table
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
}//end try
System.out.println("Goodbye!");
}//end main
//end JDBCExample
very nice tutorial here : http://www.tutorialspoint.com/jdbc/
ResultSetMetaData meta = resultset.getMetaData(); // for a valid resultset object after executing query
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = null;
while(columncount <=count) {
columnNames [i] = meta.getColumnName(i);
}
System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);
#Cyntech is right.
Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Vector<Vector<String>>tableVector = new Vector<Vector<String>>();
boolean isTableEmpty = true;
int col = 0;
while(rs.next())
{
isTableEmpty = false; //set to false since rs.next has data: this means the table is not empty
if(col != columnCount)
{
for(int x = 1;x <= columnCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
col = columnCount;
}
}
//if table is empty then get column names only
if(isTableEmpty){
for(int x=1;x<=colCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
}
rs.close();
stmt.close();
return tableVector;
ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery();
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1
String nameValuePair = "";
while (rsTst.next()) {
for (int i = 1; i < columnCount + 1; i++ ) {
String name = meta.getColumnName(i);
// Do stuff with name
String value = rsTst.getString(i); //.getObject(1);
nameValuePair = nameValuePair + name + "=" +value + ",";
//nameValuePair = nameValuePair + ", ";
}
nameValuePair = nameValuePair+"||" + "\t";
}
If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:
jdbcTemplate.query("select * from books", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
}
});
U can get column name and value from resultSet.getMetaData();
This code work for me:
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = MySQLJDBCUtil.getConnection();
preparedStatement = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
while (resultSet.next()) {
int counter = md.getColumnCount();
String colName[] = new String[counter];
Map<String, Object> field = new HashMap<>();
for (int loop = 1; loop <= counter; loop++) {
int index = loop - 1;
colName[index] = md.getColumnLabel(loop);
field.put(colName[index], resultSet.getObject(colName[index]));
}
rows.add(field);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return rows;
I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData by label instead of index:
ResultSet resultSet = null;
DatabaseMetaData metaData = null;
try {
metaData = connection.getMetaData();
resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()){
String name = resultSet.getString("COLUMN_NAME");
}
}

Categories

Resources