I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}
Related
I want to save the result of a whole Mysql table in an array
String sDriver = "com.mysql.jdbc.Driver";
String sURL = "jdbc:mysql://www.odorxd.xyz:3306/u218933149_odor_base";
try {
Class.forName(sDriver).newInstance();
Connection con = DriverManager.getConnection(sURL, "u218933149_estenoesodor", "Tsunayoshi27?");
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = con.prepareStatement("SELECT * FROM justname");
rs = stmt.executeQuery();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
System.out.print(rs.getString(x) + "\t");
}
System.out.println("");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
it returns this to me from the database
run:
brandon
Brandon
Julio
Daniel
BUILD SUCCESSFUL (total time: 1 second)
I want to save what is in the database in an array to be able to implement it with a sort and search method
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan", "Brandon", "Brandon Jesus", "Brandon Flores", "Brandon Flores Flores"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
that's why I need to save it in an array
I would appreciate any criticism or help as you do not have an idea, thank you
You can use a List.
List<String> list = new ArrayList<>();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
String str = rs.getString(x)
list.add(str);
System.out.print(str + "\t");
}
System.out.println();
}
String[] arr = list.toArray(new String[0]);
String temp;
// ... sort
Quick questions...
I'm trying to make a Dynamic JTree but I can't get to put every database I have into one single node for each one. This is my code so far:
jTree2 = new javax.swing.JTree();
try {
String DSN = "jdbc:mysql://localhost";
String user = "root";
String password = "";
conexion = DriverManager.getConnection(DSN, user, password);
}
catch(Exception e) {
System.out.println("ERROR");
}
try {
sentencia = conexion.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception e) {
System.out.println("ERROR2");
}
try {
String hi = "";
ResultSet rs1 = conexion.getMetaData().getCatalogs();
ResultSetMetaData rsmd = rs1.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++ ) {
hi = hi + rs1.getString(i) + ", ";
}
//for
String sb = hi.substring(0, hi.length()-2);
jTree2.setModel(new FileSystemModel(new File(sb)));
}
}
catch(Exception ae) {
System.out.println("ERROR3");
}
jScrollPane3.setViewportView(jTree2);
And the result I get is this:
Every database is splitted by a "," but I want them to be on a single node for each one. Any help?
This should do it for you:
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases", true);
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rs1.getString(i), true);
parent.add(node);
}
jTree2.setModel(new DefaultTreeModel(parent));
}
I use JDBC to get data from sqlite data base. In DB I have 3 column - login, password and role. I try find row by login, but it doesn't work , and I have exeption when I try getString("password") or "role", where is the mistake? Thanks
resSet = statmt.executeQuery("SELECT * FROM users WHERE login='"+login+"';");
if( hasUser( login)){
System.out.println("User finded:");
while(resSet.next()) {
System.out.println("login = " + resSet.getString("login"));
// !exeption
System.out.println("password = " + resSet.getString("password"));
// !exeption
System.out.println("role = " + resSet.getString("role"));
System.out.println();
}
}else{
System.out.println( "User not found");
}
You can check to see what column names are being returned.
ResultSetMetaData rsmd = resSet.getMetaData();
int colCount = rsmd.getColumnCount();
String rValue = "";
for (int i = 1; i <= colCount ; i++){
String name = rsmd.getColumnName(i);
rValue += name + " ";
}
System.out.println(rValue);
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
metaData.getColumnLabel(i));
}
Refer to this ans..ans see what are the names of your columns in resultant set
http://stackoverflow.com/questions/19094999/java-how-to-get-column-name-on-result-set
This is a last resort. I'm studying development of Information Systems and even my teachers can't solve this... this is a nut for you to crack!!
This is the problem: My jTable in GUI gives me this:
This is what Microsoft Management Studio shows me:
As you can tell the jTable (GUI) has got 2 main problems:
The columnname "Name" does not contain any information. And it should? Why isn't it showing?
Since as you can tell, the table contains several columns, too many to even show. I therefore want to "add a restriction" that changes so that the jTable only shows the first 6 columns.
This is the code for the "creation of the table", in the DataAccessLayer:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
String[] columnHeadings = new String[0];
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = md.getColumnName(i);
columnHeadings = Arrays.copyOf(columnHeadings, columnHeadings.length + 1);
columnHeadings[i - 1] = columnName;
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i - 1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray, columnHeadings) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
If you want me to show you the path of the code (frame, controller) just say so and I'll post it.
I would be so thankful if anyone can solve this...
Regards,
Christian
I think it is because in your for loop it should say i = 0; and not i = 1; since the first information (the name) is at index 0 right ?
In your case it could be enough to just leave the for-loop as it is and change this line to:row[i - 1] = rs.getObject(i-1);
To hide or show columns you could call setMin setMax and setPreferredWidth on your TableColumn.
Change your method like next, I think it helps you:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
List<String> columnHeadings = new ArrayList<String>();
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnHeadings.add(md.getColumnName(i));
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i-1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray,columnHeadings.toArray(new Object[columnHeadings.size()])) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE,null, ex);
}
return null;
}
For showing not all columns use dtm.setColumnCount(2);. Here 2 is column count to show.
I am using the following to add retrieved values to the class. all values will be added to attributes of the class but I am using compisition ( have an object of class in the class) and it does not show anything on output.
class employee
{
....
private Address address = new Address();
.....
}
...
Employee emp = new Employee();
try {
ps = con.prepareStatement("select * from employee,address "
+ "WHERE employee.username = ? AND "
+ "employee.ADD_ID = address.ID");
ps.setString(1, username);
ResultSet r = ps.executeQuery();
if (r.next()) {
BeanProcessor bp = new BeanProcessor();
emp = bp.toBean(r,Employee.class);
System.out.println("blockkkk:"+emp.getAddress().getBlock());
//output of above line is blockkkk:null
}
con.close();
ps.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return emp;
Address class is as following:
public class Address {
.....
private String block;
....
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
....
}
The BeanProcessor.toBean works like this:
Convert a ResultSet row into a JavaBean. This implementation uses reflection and BeanInfo classes to match column names to bean property names. Properties are matched to columns based on several factors:
The class has a writable property with the same name as a column. The name comparison is case insensitive.
The column type can be converted to the property's set method parameter type with a ResultSet.get* method. If the conversion fails (ie. the property was an int and the column was a Timestamp) an SQLException is thrown.
Primitive bean properties are set to their defaults when SQL NULL is returned from the ResultSet. Numeric fields are set to 0 and booleans are set to false. Object bean properties are set to null when SQL NULL is returned. This is the same behavior as the ResultSet get* methods.
May be the address is not a writable property. Pls do check it.
public static Object copyFromResultSet(Class clazz, ResultSet resultSet)
{
ArrayList objectArrayList = new ArrayList(1);
try
{
Object object = clazz.newInstance();
objectArrayList.add(object);
copyFromResultSet(objectArrayList, resultSet);
}
catch (Exception e)
{
e.printStackTrace();
}
return objectArrayList.get(0);
}
then:
public static void copyFromResultSet(ArrayList<Object> objectArrayList, ResultSet resultSet)
{
ArrayList arrayList = null;
try
{
if (objectArrayList != null)
{
int objectArrayList_len = objectArrayList.size();
int objectArrayList_index = 0;
java.beans.BeanInfo toBeanInfo[] = new java.beans.BeanInfo[objectArrayList_len];
Vector<Method> objectMethodVector[] = new Vector[objectArrayList_len];
Vector<Type> objectTypeVector[] = new Vector[objectArrayList_len];
int totalMethod[] = new int[objectArrayList_len];
int[][] indexes = new int[objectArrayList_len][];
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
toBeanInfo[objectArrayList_index] = java.beans.Introspector.getBeanInfo(objectArrayList.get(objectArrayList_index).getClass());
}
if (objectArrayList_len > 0 && resultSet != null)
{
Method method = null;
Type type[] = null;
int cols = 0;
String colName = null;
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
//toBeanInfo[objectArrayList_index]=java.beans.Introspector.getBeanInfo(objectArrayList.get(objectArrayList_index).getClass());
java.beans.PropertyDescriptor toPropertyDescriptor[] = toBeanInfo[objectArrayList_index].getPropertyDescriptors();
int toPropertyDescriptor_length = toPropertyDescriptor.length;
method = null;
type = null;
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
cols = resultSetMetaData.getColumnCount();
colName = null;
Vector<Method> methodVector = new Vector(cols);
Vector<Type> typeVector = new Vector(cols);
indexes[objectArrayList_index] = new int[cols];
totalMethod[objectArrayList_index] = -1;
for (int i = 1; i <= cols; i++)
{
colName = resultSetMetaData.getColumnName(i);
for (int j = 0; j < toPropertyDescriptor_length; j++)
{
if (toPropertyDescriptor[j].getName().equalsIgnoreCase(colName))
{
totalMethod[objectArrayList_index]++;
method = toPropertyDescriptor[j].getWriteMethod();
type = method.getGenericParameterTypes();
methodVector.add(method);
typeVector.add(type[0]);
indexes[objectArrayList_index][totalMethod[objectArrayList_index]] = i;
break;
}
}
}
objectMethodVector[objectArrayList_index] = (methodVector);
objectTypeVector[objectArrayList_index] = (typeVector);
}
if (resultSet.next())
{
arrayList = new ArrayList();
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
for (int i = 0; i <= totalMethod[objectArrayList_index]; i++)
{
//System.out.println(objectMethodVector[objectArrayList_index].get(i));
objectMethodVector[objectArrayList_index].get(i).invoke(objectArrayList.get(objectArrayList_index), getObject(indexes[objectArrayList_index][i], objectTypeVector[objectArrayList_index].get(i), resultSet));
}
arrayList.add(objectArrayList.get(objectArrayList_index));
}
}
while (resultSet.next())
{
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
for (int i = 0; i <= totalMethod[objectArrayList_index]; i++)
{
objectMethodVector[objectArrayList_index].get(i).invoke(objectArrayList.get(objectArrayList_index), getObject(indexes[objectArrayList_index][i], objectTypeVector[objectArrayList_index].get(i), resultSet));
}
arrayList.add(objectArrayList.get(objectArrayList_index));
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
just copy paste this code call method copyFromResultSet(class, ResultSet )
pass two perameters first is class name and second is resultset.
i am sure this is working properlly