how to delete selected row without affecting the same custno in deleting
the code show this error java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
model = (DefaultTableModel) jTransTable.getModel();
int SelectedRows = jTransTable.getSelectedRow();
try{
int id = Integer.parseInt(model.getValueAt(SelectedRows, 0).toString());
int deleteItem = JOptionPane.showConfirmDialog(null, "Confirm if you want to Delete Data",
"Warning", JOptionPane.YES_NO_OPTION);
if (deleteItem == JOptionPane.YES_OPTION){
Connection con = DBConnection.getConnection();
PreparedStatement add=con.prepareStatement("DELETE FROM transaction WHERE CustNo=" +id);
add.setInt(1, id);
add.executeUpdate();
JOptionPane.showMessageDialog(this,"Record Deleted Successfully");
//refresh overview
new Overview().setVisible(true);
this.dispose();
}
}catch(Exception e){
e.printStackTrace();
}
Related
I want to get followers Id's for a particular userId using java program. where I want to implement the cursor concept with rate limit set ... Can any one post me the code.
Use the following code snippet to get follower id. After getting the ids you use show user to get other details. Remember to use this code in background thread like in asynctask.
long[] tempids = null;
ConfigurationBuilder config =
new ConfigurationBuilder()
.setOAuthConsumerKey(custkey)
.setOAuthConsumerSecret(custsecret)
.setOAuthAccessToken(accesstoken)
.setOAuthAccessTokenSecret(accesssecret);
twitter1 = new TwitterFactory(config.build()).getInstance();
while(cursor != 0) {
try {
IDs temp = twitter1.friendsFollowers().getFollowersIDs("username", cursor);
cursor = temp.getNextCursor();
tempids = temp.getIDs();
} catch (twitter4j.TwitterException e) {
System.out.println("twitter: failed");
e.printStackTrace();
return null;
}
if(tempids != null) {
for (long id : tempids) {
ids.add(id);
System.out.println("followerID: " + id);
}
}
}
I am trying to populate a ComboBox with a list that is populated by a SQL statement.
I tried this:
public void buildData(){
ObservableList<ComboBox> data = FXCollections.observableArrayList();
Connection conn = db.makeConnection();
try{
String SQL = "Select Feature from FeaturesTable Order By Feature";
ResultSet rs = conn.createStatement().executeQuery(SQL);
while(rs.next()){
ComboBox cb = new ComboBox();
cb.featureCombo.set(rs.getString("Feature"));
featureCombo.add(cb);
}
featureCombo.setItems(data);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
I'm getting an error under cb.featureCombo.set of "featureCombo cannot be resolved or is not a field" but featureCombo exists as:
#FXML
private ObservableList<ComboBox> featureCombo;
and then another error under featureCombo.setItems(data); probably because of the same problem.
I'm not set on this method if someone has a better way to do this.
If you desire a ComboBox named featureCombo, you are going to have to declare it as a ComboBox and not as private ObservableList<ComboBox> featureCombo; which is making an ObservableList
Something like
#FXML
ComboBox<String> featureCombo;
Then in your method, you need to make a list of String to populate the ComboBox (you currently have a list of ComboBox)
public void buildData(){
ObservableList<String> data = FXCollections.observableArrayList(); //List of String
Connection conn = db.makeConnection();
try{
String SQL = "Select Feature from FeaturesTable Order By Feature";
ResultSet rs = conn.createStatement().executeQuery(SQL);
while(rs.next()){
data.add(rs.getString("Feature")); //add the String to the list
}
featureCombo.setItems(data); //Set the list of String as the data for your combo box
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
I am having a weird post back problem. I have two dropdowns, project and charge codes. Projects selection populates the charge code drop down. I noticed that when I select a charge code, the value appears in the dropdown for a split second and then changes to the first choice in the dropdown. The Index change of that dropdown triggers and the value is the first option in the dropdown, not the one selected. I am not sure why it's doing this, but it must have something to do with postback. If it is a postback problem, is there a way to store the dropdown selection and restore the selection after re-load? Please don't suggest using AJAX or update panels, as we aren't allowed. Here is my asp code:
<p>
<asp:DropDownList ID="ddlProjects" runat="server"
onselectedindexchanged="ddlProjects_SelectedIndexChanged"
AutoPostBack="True" Visible="false" >
</asp:DropDownList>
</p>
<asp:DropDownList ID="ddlChargeCodes" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlChargeCodes_SelectedIndexChanged" Visible="false">
</asp:DropDownList>
<p>
and the C# code behind:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
LoadProjectsDropDown();
}
//Rest of Pageload Omitted....
// Initial Population of Project Dropdown
protected void LoadProjectsDropDown()
{
try
{ // Populate the Projects Drop Down from Table
ddlProjects.Items.Clear();
ddlProjects.DataSource = Time_Tracker.BLL.ProjectsManager.GetItems();
ddlProjects.DataTextField = "Project_Name";
ddlProjects.DataValueField = "Project_ID";
ddlProjects.DataBind();
ddlProjects.Items.Insert(0, new ListItem("PLEASE SELECT A PROJECT",
"PLEASE SELECT A PROJECT"));
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace,
#"Time_Tracker.txt");
}
}
// The Index Change portion of the Project Dropdown, which builds the Charge Code dropdown
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
ddlChargeCodes.DataSource = Time_Tracker.BLL.TasksManager.GetChargeCodes
(ddlProjects.SelectedValue);
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Project_ID";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, new ListItem("PLEASE SELECT A CHARGE
CODE", "PLEASE SELECT A CHARGE CODE"));
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
// The Index Change of the Charge Codes Dropdown
protected void ddlChargeCodes_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Charge Code, it shows a summary and asks for the number of hours
Utilities.Description = Convert.ToString(ddlChargeCodes.SelectedItem);
Utilities.Chargecode = Convert.ToString(ddlChargeCodes.SelectedItem);
lblHoursLabel.Visible = true;
txtHours.Visible = true;
lblConfirmation.Visible = true;
btnStarOver.Visible = true;
btnOK.Visible = true;
lblConfirmation.Text = "Hours on " + Utilities.SelectedDate + " For Charge Code " + Utilities.Description;
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
Did a lot of troubleshooting today. found that upon selecting the chargecode, it would do a pageload without triggering the "change index" event handler. Upon completion of pageload, it would trigger the index change event with the first selection (index 1) selected. Everyone I talked to said it should work the way it is. I finally wrote out the query/databind part of it to populate the dropdown instead of using the stored procedure and it now works. I have included the code change if it will help people in the future.
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
string strConn = Time_Tracker.DAL.DBUtils.SqlConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Charge_Code, Charge_Code + ' - ' + Description AS Description FROM [Time_Tracker].[dbo].[Tasks] WHERE Inactive = 0 AND Project_ID = " + ddlProjects.SelectedValue;
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlChargeCodes.DataSource = objDs.Tables[0];
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Charge_Code";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, "PLEASE SELECT A CHARGE CODE");
}
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;
I have a problem. When I try to use the "Select distinct" in HSQLDB, the stream of results returns me all rows instead of me returning only distinct rows.
I've tried the following syntax:
SELECT DISTINCT FROM ratings UserID order by UserID;
SELECT DISTINCT (UserID) FROM ratings order by UserID;
SELECT DISTINCT UserID FROM ratings;
SELECT DISTINCT (UserID) FROM ratings;
None of them works. What is the problem?
If anyone able to help me I appreciate.
Thank you.
The function code where I perform the action is as follows:
private void readUserFile(String filename) {
try {
//Verify if file users exists
boolean exists = (new File(filename)).exists();
if (!exists) {
//If file users not exists create one, bases on distinct users that exist in ratings table
ResultSet rsUsers = jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("SELECT DISTINCT UserID FROM ratings order by UserID;");
List<String> users = new ArrayList<String>();
while (rsUsers.next()) {
users.add(String.valueOf(rsUsers.getInt(1)));
}
rsUsers.close();
//Create and write to file
BufferedWriter f = null;
f = new BufferedWriter(new FileWriter(filename));
for (String user : users) {
f.write(user);
f.newLine();
}
f.close();
}
PreparedStatement prstInsert = con.prepareStatement("INSERT INTO users VALUES (?)");
BufferedReader in = new BufferedReader(new FileReader(filename));
int i = 0;
while (true) {
String s = in.readLine();
if (s == null) { // end of file
log.info("Total imported users: " + i);
break;
}
i++;
int userid = Integer.parseInt(s);
prstInsert.setInt(1, userid);
if (i != 0 && Math.round((double) i / 100) == ((double) i / 100)) {
log.info("Imported users: " + i);
}
prstInsert.executeUpdate();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}