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);
}
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 want to insert input given by user into Sql Table using Java, but dont know how many coloumn is need.
eg.
insert into table_name values('"+id+"','"+name+"')
this query is not going to work because I don't know the column name i.e ID, name.
I want the query that is universal for any inserting data.
As per my need I tried this code. I HOPE IT WORKED FOR ALL.
void getTableInput(String tname, String dname) throws ClassNotFoundException, SQLException {
this.tname = tname;
this.dname = dname;
Scanner s = new Scanner(System.in);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String conURL = "jdbc:sqlserver://localhost:1433;databaseName=" + this.dname + ";user=JT_DATA;password=1234";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM " + this.tname);
ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
String colName[] = new String[colNo];
String[] get_User_Input = new String[100];
for (int i = 1; i <=colNo; i++)
{
colName[i-1] = rsmd.getColumnLabel(i);
System.out.print(Arrays.toString(colName) + " : ");
get_User_Input[i-1] = s.next();
}
String store="";
for(int i=0;i<colNo;i++)
{
store += "'"+get_User_Input[i]+"',";
}
store = store.substring(0,store.length() -1);
PreparedStatement pst = con.prepareStatement("insert into "+this.tname+" values ("+ store +")");
pst.executeUpdate();
System.out.println("Data Inserted");
}
But the problem with this is that. This can only insert String Datatype.
I dont think there is any universal query.
If you dont know column name than you can find name of the column by using meta data.
You can get meta data of the connections (database)
DatabaseMetaData databaseMetaData = connection.getMetaData();
You can also get list of the tables.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
while(result.next()) {
String tableName = result.getString(3);
}
Listing column name in table.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;
ResultSet result = databaseMetaData.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern);
while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
In this way you can find column name and can create query dynamically.
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.
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));
}
}