I have a sqlite databse, with alot of tables. Each table has many rows. In one column I have something like this:
[58458, 65856, 75658, 98456, 98578, ... N]
I made a mistake when created the databse (I don't have acces to the initial data anymore ), what I need is to make these numbers with a punct after the second digit and have something like this:
[58.458, 65.856, 75.658, 98.456, 98.578, ... N]
Is there any way I can do this? I prefer Java. Or is it already any tools that can do this?
Use this function to parse the information from each column.
public static String convertColumn(String textF)
{
String textAux = "";
String newText = "[";
int i = 0;
textF = textF.substring(1, textF.length() - 1);
while(i < textF.length())
{
textAux = textF.substring(i, i + 5);
int nrAux = Integer.parseInt(textAux);
i+=7;
int a;
int b;
a = nrAux / 1000;
b = nrAux - a * 1000;
double newNr;
newNr = a + b * 0.001;
newText = newText + newNr + ", ";
}
newText = newText.substring(0, newText.length() - 2);
newText += "]";
return newText;
}
The function will have as parameter a string like [58458, 65856, 75658, 98456, 98578], which you will get from
the SQL table, and the return value will be [58.458, 65.856, 75.658, 98.456, 98.578] which is the value that you need to update the column with.
For SQL the base idea is this:
UPDATE table
SET column = convertColumn(column);
You can use CAST as REAL on the column, and then update as advised in the other answer.
select CAST(YOUR_COL AS REAL) from YOUR_TABLE
Search for CAST in this doc for more info on it: SQLite language guide
This should work if it's a NUMERIC column:
UPDATE <TABLE NAME> SET <COLUMN> = <COLUMN>/1000;
If it is NOT a NUMERIC or REAL column then this should work:
UPDATE <TABLE NAME> SET <COLUMN> = CAST(<COLUMN> AS REAL)/1000;
(Thanks to Goibniu for the pointer)
Related
Hopefully i will explain clear enough, I have a List of objects ( each object have 3 properties ) those objects are printed to xls file, I am trying to locate the cell where the value were assigned first and the last in order to get a references and setFormula to get Sum of all of the middle values
public String getCellReference(int rowPosition, int cellPosition) {
CellReference reference = new CellReference(rowPosition, cellPosition);
return reference.formatAsString();
}
public String getCellReference(int rowPosition, int cellPosition) {
CellReference reference = new CellReference(rowPosition, cellPosition);
return reference.formatAsString();
}
public String getSumFormula(int rowPosition, int cellPosition, int rowPosition2, int cellPosition2) {
String startCell = getCellReference(rowPosition, cellPosition);
String finishCell = getCellReference(rowPosition2, cellPosition2);
return "SUM(" + startCell + ":" + finishCell + ")";
}
To locate first value and last its not a problem but its seems to be a problem for me to locate a cell indexes
public Cell locateCell(List<Invoice> invoices){
BigDecimal firstGeneralTotal = invoices.get(0).generalTotal();
BigDecimal lastGeneralTotal = invoices.get(invoices.size()-1).generalTotal();
}
Basic access using POI would be like this:
XSSFWorkbook wb = new XSSFWorkbook( … );
XSSFSheet sheet = workbook1.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
XSSFCell cell = row.getCell(0);
String value = cell.getStringCellValue();
Instead of using getStringCellValue you can also use one of those methods:
cell.getCellFormula()
cell.getNumericCellValue()
cell.getBooleanCellValue()
cell.getErrorCellValue()
Accordingly, you can do cell.setCellFormula(String formula) to set a cell.
If you want to add a formular to the end of the table containing the sum, you could use the cell references if you like. In this case, you'd need to find the last row in the excel sheet:
sheet.getPhysicalNumberOfRows()
Then you could add a new row to the end of your sheet:
sheet.createRow(sheet.getPhysicalNumberOfRows()+1);
and put your sum in according cell.
Btw, I am not sure if I would use CellReferences, since they can contain references to other sheets as well. If I work only with a single sheet, I'd try to use the index numbers and translate them accordingly to A1:A200 etc.
Does this help you? If I got your question wrong, let me know in the comments, I may update my answer if possible.
public String getCellReference(int rowPosition, int cellPosition) {
CellReference reference = new CellReference(rowPosition, cellPosition);
return reference.formatAsString();
}
public String getCoefficientFormula(int startRow, int firstCell, int endRow, int lastCell) {
String firstReference = getCellReference(startRow, firstCell);
String lastReference = getCellReference(endRow, lastCell);
return firstReference + "/" + lastReference;
}
public String getSumFormula(int startRow, int endRow, int start, int finish) {
String startCell = getCellReference(startRow,start);
String finishCell = getCellReference(endRow,finish);
return "SUM(" + startCell + ":" + finishCell + ")";
}
I want to get table label of column .like string display in mysql. Like this
However, when I use getColumnName, It turn out there is some difference between returned string and below string. Like this:
But It is right in Variables explorer in eclipse when I debug, Like this:
I can't find other way to get column. It seem returned string is originalColumnName, but how to get ColumnName? Anyone know how to fix it?
There is my code, I know there is other problem in code. Please just assume the type of all column is String.
public ResultSet DisplayShowTables() throws SQLException
{
ResultSet Res = Sta.executeQuery("DESC Code2Name");
ResultSetMetaData ResMeta = Res.getMetaData();
String [] ColumnName = new String [ResMeta.getColumnCount()];
int MetaCount = ResMeta.getColumnCount();
for (int i = 0; i < MetaCount; i++) {
ColumnName [i] = ResMeta.getColumnName(i+1);
}
String LeftAlignFormat = "|";
String Separator = "+";
for (int i = 0; i < MetaCount; i++) {
LeftAlignFormat = LeftAlignFormat.concat(" %-20s |");
Separator =Separator.concat("----------------------+");
}
LeftAlignFormat = LeftAlignFormat.concat("%n");
Separator = Separator.concat("%n");
if(Res.isBeforeFirst()){
System.out.format(Separator);
System.out.format(LeftAlignFormat, ColumnName);
System.out.format(Separator);
}
while (Res.next()) {
Vector<String> RowData = new Vector<String>();
for (int i = 0; i < MetaCount; i++) {
RowData.add(Res.getString(i+1).toString());
}
System.out.format(LeftAlignFormat, RowData);
}
if(Res.isAfterLast())
System.out.format(Separator);
return Res;
}
It looks like DESC is just a shortcut for a query of the information schema with aliases for the columns.
Column aliases can be retrieved with ResultSetMetadata.getColumnLabel(int).
JDBC defines column label as:
Gets the designated column's suggested title for use in printouts and displays. The suggested title is usually specified by the SQL AS clause. If a SQL AS is not specified, the value returned from getColumnLabel will be the same as the value returned by the getColumnName method.
This also means that in almost all situation you should be using getColumnLabel instead of getColumnName.
I have a list of objects List , being the result of a HQL Query. The Objects of the list contain the data I need. I am doing the following if I know the types of the data :
(Here I know that the query was Select country, globalAmount, average from table)
for (Object record : result) {
Object[] fields = (Object[]) record;
String country = (String) fields[0];
long globalAmount = (Long) fields[1];
double average = (Double) fields[2];
System.out.println("Country "+country );
System.out.println("Global Amount "+globalAmount);
}
The problem is that sometimes, I don't know if I'll be having "Country" or "average" in the Object, and the query can be completely different :
Select average, date, message from table
Then, to retreive data, I have to do the following :
for (Object record : result) {
Object[] fields = (Object[]) record;
double average = (Double) fields[0];
Timestamp date= (Timestamp) fields[1];
String message = (String) fields[2];
System.out.println("date " +date);
System.out.println("Message "+Message);
System.out.println("Average " + Average);
}
Is there any way that I can dynamically retreive data from this List without having Cast problems?
Thank you for your help!
This is just a proto-type. What I did here is got all the column names and then based on the column name I'm type casting it to the required type.
This is just a small trick.
String query = "Select x, y, z from tablename";
//get the columns here
String colums = query.substring(7, query.indexOf("from") - 1).trim();
String []arrColums = colums.split(",");
for(int i = 0; i < arrColums.length; i++)
{
switch(arrColums[i])
{
case "X" : X x = (X)result.get(i);
case "Y" : Y y = (Y)result.get(i);
}
}
It does not to seem possible. I had to use If blocks to figure out which type I am receiving. Quite long but did not have any other option. The solution provided by Uma Kanth is smart but was not suitable for me though.
I have different tables in a database(say mysql). i need to extract some columns from different table and write it in a csv file. consider table 1
A 1
B 2
C 3
table 2 table 3
X 7 AB A1
Y 8 BC B2
Z 10 CD C3
U 11 DE D4
V 12
W 13
i want to write 1st column from table 1,2nd col from table 2, and 1st col from table 3 in a csv file such that empty rows are made null.
output:
A,7,AB
B,8.BC
C,10,CD
null,11,DE
null,12,null
null,13,null
i can do the basic reading and writing from mysql to csv, need help in the logic or code to get the above output. "Looking for a generic solution for say 'n' number of columns from 'n' number of tables". above is jus a example.
I do not know how you read your database but assume you do it with JDBC:
ResultSet tableAReusltSet= null;
ResultSet tableBReusltSet= null;
ResultSet tableCReusltSet= null;
List<PseudeContainer> container = new ArrayList<>();
while (tableAReusltSet.next()) {
PseudeConteiner ps = new PseudoContainer();
ps.col1 = tableAReusltSet.getString("ColumnName");
container.add(ps);
}
int i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
//.. now you have a collection to work with which you can write
public PseudeContainer {
String col1 = null;
String col2 = null;
String col3 = null;
}
Above should work.. still pseudo code...
Since you just want the logic here is some pseudo code that may help you in whatever language you are using. Since I don't know how you are exporting to csv I made it pretty generic.
arr1 = select column1 from table1;
arr2 = select column2 from table2;
arr3 = select column1 from table3;
max = isBigger(arr1.length, arr2.length);
max = isBigger(max, arr3.length);
for(i=0; i<max; i++)
{
if(arr1[i]=="") arr1[i]=null;
if(arr2[i]=="") arr2[i]=null;
if(arr3[i]=="") arr3[i]=null;
print arr1[i] + "," + arr2[i] + "," + arr3[i];
}
Recommend 3rd party libraries to handle CSV files:
Apache Commons CSV
Open CSV
So I am trying to get the result as count from a sql query as follows
ResultSet rs = st.executeQuery("SELECT count(employeeID) FROM employee WHERE " +
"employeeID='"+_empID+"' AND password = '"+_password + "'");
so i am also trying to convert that value to int and I tried the follwing
for (; rs.next();) {
val = (Integer) rs.getObject(1);
}
I have also try
val = Integer.parseInt(rs.getObject(1));
but nothing I get the following errors
java.lang.Long cannot be cast to java.lang.Integer
How can I do this.. so if that returns a 0,3 or 4 that it becomes an integer?
Thank you
EDITED TO: (STILL GETTING ERROR)
long countLong = 0;
for (; rs.next();) {
countLong = rs.getLong(1);
}
if(countLong < 1)
{
isAuthentic = false;
}
else
{
isAuthentic = true;
}
A good trick to use when you are not sure about the exact number type is to cast it to the parent class of all numeric type, Number:
val = ((Number) rs.getObject(1)).intValue();
This will work for all numeric types, eg float, long, int etc.
Use ResultSet.getLong method:
long countLong = resultSet.getLong(1);
//if you really want and you are sure that it fits you can now cast
int count = (int)countLong;
Try a getString() and then Long.parseLong().
Cast it to a string and then to an int or long or whatever you want:
Integer.parseInt(rs.getObject(1).toString());