My program has an auto incremented ID with the format of ITM001, ITM002.... But after ITM009, ITM0010 the sequence is broken and goes back to ITM001. Because of that I'm getting ITM0010 as next item ID instead of ITM0011. Please help me to understand how should I write the query to continue the sequence.
ITM001
**ITM0010**
ITM002
ITM003
ITM004
ITM005
ITM006
ITM007
ITM008
ITM009
Connection conn = DBConnection.conn();
String sql = "select itemId from ItemMain";
ResultSet res = DBHandller.getData(sql, conn);
if (res.last()) {
String lastid = res.getString("itemId");
return lastid;
}
return null;
/////////////////////////////////////////////////////////////////////////////
String itemID = ItemController.getItemID();
String[] split = itemID.split("ITM",0);
int num = Integer.parseInt(split[1]);
itemID = "ITM00"+ (num+1);
txtitemID.setText(itemID);
The problem is that you're using split on 0, and there are several 0's in your String after you increment, for instance:
String[] split = itemID.split("ITM",0);
int num = Integer.parseInt(split[1]);
String second = "ITM00" + (num + 1);
System.out.println(second);
System.out.println(Arrays.toString(second.split("0")));
This will output:
[ITM, , 1]
Since the last 0 will also be split.
Something like:
String itemID = "ITM009";
int num = Integer.parseInt(itemID.substring(itemID.indexOf("0")));
String second = "ITM0" + String.format("%02d", num + 1);
System.out.println(second);
Will give you what you want probably, but you need to figure out how many digits you want your key to have and adapt accordingly.
You are implicitly sorting on a VARCHAR field.
SELECT a.a FROM (
SELECT 'a001' [a]
UNION ALL
SELECT 'a009' [a]
UNION ALL
SELECT 'a0010' [a]
) a ORDER BY a
a001
a0010
a009
The last id you pick up will always be 009 so the next one you create will always be 0010.
If you front padded the "10" with 1 "0" instead of two the implicit ascending sorting would be correct. "001 ... 009, 010"
Related
How do i create the one line expression using Java swing, link image picture. the every minute, every day,every month, every weekday and every hour need to convert it to "*" and also all the combo box contain the list of number list number link and weekday contain the click the picture
what i want is, if the user select "Every Minute" , "Every day","month = 2", "Weekday = monday", "hour= 3"
note of weekday JCombo : sunday = 0 , monday = 1, tuesday = 2 .....
the output will print as : * * 2 1 3
thanks alot.
i already tried this , my beginning code but cant do much :
String sjcb_EM = jcb_EM.getSelectedItem().toString();
String sjcb_EH = jcb_EH.getSelectedItem().toString();
String sjcb_ED = jcb_ED.getSelectedItem().toString();
String sjcb_EEM = jcb_EEM.getSelectedItem().toString();
String sjcb_EW = jcb_EW.getSelectedItem().toString();
String vb_1 = sjcb_EM + " " + sjcb_EH + " " + sjcb_ED + " " + sjcb_EEM + " " + sjcb_EW;
System.out.println(vb_1);
now i stuck, how to make the expression that i wanted.
Start by building a class which can hold both the display value and the query value...
public class WorkoutUnit {
private String displayValue;
private String queryValue;
public WorkoutUnit(String displayValue, String queryValue) {
this.displayValue = displayValue;
this.queryValue = queryValue;
}
public String getDisplayValue() {
return displayValue;
}
public String getQueryValue() {
return queryValue;
}
#Override
public String toString() {
return displayValue;
}
}
Build a ComboBoxModel using these values...
DefaultComboBoxModel<WorkoutUnit> model = new DefaultComboBoxModel<>();
model.addElement(new WorkoutUnit("Every Minute", "*"));
for (int index = 10; index < 61; index += 10) {
model.addElement(new WorkoutUnit(Integer.toString(index), Integer.toString(index)));
}
JComboBox<WorkoutUnit> cb = new JComboBox(model);
When needed, get the selected item from the combo box and get its query value...
WorkoutUnit unit = (WorkoutUnit)cb.getSelectedItem();
System.out.println("Query = " + unit.getQueryValue());
In this example, I've used toString to provide the display value to the JComboBox, this is not my preferred solution, I'd prefer to use a ListCellRenderer as demonstrated here
Oh, and because it looks like you're heading down a database query route, you should also have a look at Using Prepared Statements
I have a string that might look like this:
searchText = search:kind:(reports) unit.id:(("CATS (WILLIAMS)"~1) OR ("DOGS (JAMES)"~1))
I need to extact any values that may exist in the quotation marks so in this case it would be:
CATS (WILLIAMS) and DOGS (JAMES)
Not sure I understand how using indexOf and subString will get me a text string since they depend on integer values... Can someone show me some examples of how this might be done? Thanks
Ok figured out the basics, but I need it to extract every value in " " not just the first instance. The below extacts the value then converts the name into an id then replaces the name with an id, but ONLY does the first instance.
String unitIdStart = "\"";
String unitIdEnd = "\"~";
int unitIdStartIndex = searchText.indexOf(unitIdStart);
if( unitIdStartIndex != -1 ) {
int unitIdEndIndex = searchText.indexOf(unitIdEnd, unitIdStartIndex);
if( unitIdEndIndex != -1 );
{
String unitName = searchText.substring(unitIdStartIndex+1, unitIdEndIndex);
Unit backToId = UnitRepository.getIdFromName(unitName);
String unitId = backToId.getId().toString();
String searchTextWithUnitId = searchText.replace(unitName, unitId);
Here's the table (tblemployees)
How can I convert my code that used text files to a code that will use database (tables).
int intcurrentLine = -1;
String[] strLineSplit = (sb.toString()).split("\\r?\\n"); // converts sb to string then splits it by line
int intNumElements = strLineSplit.length; // number of elements
while (intcurrentLine != (intNumElements - 1)) {
intcurrentLine++;
String[] strWords = (strLineSplit[intcurrentLine]).split(" ", 2); // splits the current line by the first instance(space)
if (strEmpID.equals(strWords[0])) { // checks if the employee ID is available
JOptionPane.showMessageDialog(null, "Welcome " + strWords[1] + ", you have successfully logged in.");
strCheck = 1; // to confirm and go to time in and out process
break;
}
if ((intcurrentLine + 1) == intNumElements) { // condition to state that ID cant be found from the employee list
JOptionPane.showMessageDialog(null, "No such employee, please check the ID No. that you entered.");
}
}
Now I would like to search a column if it contains an Employee number. How do I put it to a condition, I've been searching but unable to find a clear answer. They only put how to search like this
String queryCheck = "SELECT * from messages WHERE EmpIDNo = 'COMSCI0001'";
ResultSet res = st.executeQuery(queryCheck);
then I'm lost, how to make a condition where if the employee no. doesn't exists something would happen else something would happen. I'm just confuse how to make a condition for that.
You can do like this:
String queryCheck = "SELECT * FROM messages WHERE EmpIDNo = 'COMSCI0001' LIMIT 1";
ResultSet res = st.executeQuery(queryCheck);
boolean exists = res.next();
The boolean variable exists will indicate whether a matching record exists or not.
Notice that I added LIMIT 1 at the end of the SQL as an optimization to avoid fetching more data than you really need.
I have a array list of integers . I want to use this list in the IN clause of SQL query. I tried to do the below, but i know it wont work. Can someone suggest a better way .
List<Integer> **plcList** = new ArrayList<Integer>();
String finalQuery = "
select plc,direction,ROUND(AVG(CAST(speed as float)),2) as speed,COUNT(plc) as count,time_id
from processed
WHERE plc IN " + " " + "(**plcList**)"+ " " + "
group by plc, direction, time_id";
I suggest to have a look on this one: PreparedStatement IN clause alternatives?
And this page: http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
In your case, you could just loop to build the integer list as Abdul mentioned above.
I am not a Java prof. but I would suggest you to loop throug your list and make string with comma seperated values. Like in PHP we do this with implode function. And hence your final string would be something like this
1,2,3,4,5
and then use it in your sql query
I am not sure about my code but try this as I am not a Java programmar (
make the necessary changes if any syntax error)
String intlist = "";
for (String temp : list)
{
intlist += ","+temp;
}
String Str = new String(intlist);
String sqlstring = Str.substring(1);
Try this..
List<Integer> myList = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
// length of the list
int locSize = myList.size();
Object[] args = new Object[locSize];
for( int i = 0; i < locSize; i++ ) {
builder.append(" ?, " );
args[i]= myList.get(i);
}
You can then use this in your query, something like this.
....WHERE plc IN ("+ builder.toString() +") group by plc, direction, time_id";
Refer passing object[] to sql query for similar question.
For example,
consider this as a string
a.prd_id IN
( SELECT prd_id FROM prd)
I need to replace the text after SELECT i.e. prd_id to period and don't want to change the prd_id that is coming after "a.prd_id"
Sample output :
a.prd_id IN
( SELECT period FROM prd)
Where ever the prd_id is coming after the 'Select' keyword I have to replace it with 'period'
You can use a positive look behind to achieve this.
(?i)(?<=SELECT\s)\s*prd_id\b
You will need positive lookbehind:
String s="a.prd_id IN\n" +
"( SELECT prd_id FROM prd)";
System.out.println("Replaced => " +
s.replaceAll("(?i)(?<=\\bSELECT)(\\s+)prd_id\\b", "$1period"));
OUTPUT:
Replaced => a.prd_id IN
( SELECT period FROM prd)
Try this,
String inputString = "a.prd_id IN (SELECT prd_id FROM prd)";
String constantSelect = "SELECT";
String constantFrom = "FROM";
String tmpString = "", resultString = "";
int startIndex = inputString.indexOf(constantSelect);
int endIndex = inputString.indexOf(constantFrom);
tmpString = inputString.subString((startIndex + constantSelect.length), endIndex).trim;
resultString = inputString.replace(tmpString, "Your new string");
a.substring(a.indexOf("(")+1,a.indexOf(")")).replace("prd_id", "?") where a is your string and '?' will be your replaced string