JavaFX combo box repeating the same value set - javafx

I used a combo box to retrieve data from MySQL database. But when i inserted the first value set to database, combo box values are repeating. I want to know why it is happening and how to avoid it. i called this method on main. Thanks
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
op.add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}

Add a condition that checks if the String you wanna insert is already in op,
I assume op type is ObservableList<String>. This should work :
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
if(!op.contains(rs.getString("Name"))
add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}

Related

JavaFX delete datarow in tableview and sqlite

I would like to delete a row in tableview but also in the
underlying SQLite Database which populate the tableview
Here I get the selectedRow
public void deleteDBRow() {
if (tableV.getSelectionModel().getSelectedItem() != null) {
Bew selBew = tableV.getSelectionModel().getSelectedItem();
System.out.println(selBew.getName());
}
}
and can delete it with casual code
DELETE FROM Table WHERE name = ""+selBew.getName()");
But I would like to delete the entry in the sqlite database also
From time to time I have rows with the same text in every column - so this way
was critical - can I use rowID to delete the selected row in sqlite?
Here one try from me to get rowid in tableview
ObservableList bewList = FXCollections.observableArrayList();
try {
String sql = "SELECT rowID, Name, Date, Action, Info FROM tab1";
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB1.db");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
bewList.add(new Bew(rs.getInt("rowID"), rs.getString("name"), rs.getString("date"),
rs.getString("action"), rs.getString("Info")));
System.out.println("rs.next : " + rs.getInt("rowID") +" - " + rs.getString("date") +" " +
rs.getString("action") +" " + rs.getString("Info"));
}
}catch (Exception e) {
System.out.println("SQLiteDB.getData ---> Error RS");
System.err.println("*E"+e.getClass().getName() + ": " + e.getMessage());
}
return bewList;
String sql = "CREATE TABLE IF NOT EXISTS tab1" +
"(rowID INT PRIMARY KEY," +
"NAME CHAR(50) NOT NULL ,"+
"DATE CHAR(15) ,"+
"ACTION CHAR(50) ,"+
"INFO CHAR(3));";
conn.createStatement().executeUpdate(sql);
rowID ist always 0 - don't know why ???
edit:
Controller
ObservableList bewList = DB.getData();
tableV.setItems(bewList);
Edit:
Maybe error in here - add data
i add 4 values - rowid missing??
public void add(String Name, String Date, String Action, String Info) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB2.db");
stmt = conn.createStatement();
String ValStr = "\'"+Name+"\' ,\'"+Date+"\',\'"+Action+"\' ,\'"+Info+"\'";
String sql = "INSERT INTO tab1 (rowID, NAME,DATE,ACTION, INFO) VALUES ("+ValStr+")";
// System.out.println("Button Click add"+conn.createStatement().toString());
stmt.executeUpdate(sql); //geƤndert
ObservableList<Bew> list = getData();
conn.close();
System.out.println("DB ROW add");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

Update a column if row exists, and insert row if it doesn't

I have a table INVENTORY with 2 columns [product(primary key) - quantity]. I want to insert to this table a product with its quantity.
public boolean insertPackage(String product, int quantity)
throws SQLException, ClassNotFoundException {
System.out.println("Insert product to Invetory");
boolean flag=false;
sq = "INSERT INTO INVENTORY VALUES (?, ?)";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
stm.setString(1, product);
stm.setInt(2, quantity);
int rowsAffected = stm.executeUpdate();
} catch (SQLException e) {
//There is already a same product in the Inventory
flag = true;
System.out.println(e.getMessage());
} finally {
if (stm != null)
stm.close();
if (c != null)
c.close();
}
return flag; //if the flag is true, then execute insert.
}
If it returns true, then I search for this product, retrieve the quantity and then update the table with the new quantity. I am wondering if this way I thought, is a good way to check how to perform the insertion or there is a better one.
In your particular case the easiest solution would be to use SQLite's INSERT OR REPLACE syntax, like so:
public static void main(String[] args) {
String connectionURL = "jdbc:sqlite:"; // in-memory database
try (Connection conn = DriverManager.getConnection(connectionURL)) {
// set up test data
try (Statement st = conn.createStatement()) {
st.execute("CREATE TABLE INVENTORY (product VARCHAR(10) PRIMARY KEY, quantity INT)");
st.execute("INSERT INTO INVENTORY (product, quantity) VALUES ('one', 123)");
}
System.out.println("Initial state:");
dumpTable(conn);
// real code starts here
String sql = "INSERT OR REPLACE INTO INVENTORY (product, quantity) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "two"); // product is new, so it will insert
ps.setInt(2, 234);
ps.executeUpdate();
System.out.println();
System.out.println("First change:");
dumpTable(conn);
ps.setString(1, "one"); // product already exists, so it will replace
ps.setInt(2, 999);
ps.executeUpdate();
System.out.println();
System.out.println("Second change:");
dumpTable(conn);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private static void dumpTable(Connection conn) throws SQLException {
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT product, quantity FROM INVENTORY ORDER BY product")) {
while (rs.next()) {
System.out.printf(
"product \"%s\" - quantity: %d%n",
rs.getString("product"),
rs.getInt("quantity"));
}
}
}
However, INSERT OR REPLACE in SQLite is really just a DELETE followed by INSERT, so another solution would be to try and do the UPDATE first, then do an INSERT if the UPDATE doesn't affect any rows. (That might be more efficient if you tend to be doing more updates than inserts.)
public static void main(String[] args) {
String connectionURL = "jdbc:sqlite:"; // in-memory database
try (Connection conn = DriverManager.getConnection(connectionURL)) {
// set up test data
try (Statement st = conn.createStatement()) {
st.execute("CREATE TABLE INVENTORY (product VARCHAR(10) PRIMARY KEY, quantity INT)");
st.execute("INSERT INTO INVENTORY (product, quantity) VALUES ('one', 123)");
}
System.out.println("Initial state:");
dumpTable(conn);
// real code starts here
updateQuantity("two", 234, conn);
System.out.println();
System.out.println("First update:");
dumpTable(conn);
updateQuantity("one", 999, conn);
System.out.println();
System.out.println("Second update:");
dumpTable(conn);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private static void updateQuantity(String theProduct, int newQuantity, Connection conn) throws SQLException {
int rowsAffected;
try (PreparedStatement psUpdate = conn.prepareStatement("UPDATE INVENTORY SET quantity=? WHERE product=?")) {
psUpdate.setInt(1, newQuantity);
psUpdate.setString(2, theProduct);
rowsAffected = psUpdate.executeUpdate();
}
if (rowsAffected == 0) {
try (PreparedStatement psInsert = conn.prepareStatement("INSERT INTO INVENTORY (product, quantity) VALUES (?, ?)")) {
psInsert.setString(1, theProduct);
psInsert.setInt(2, newQuantity);
psInsert.executeUpdate();
}
}
}
private static void dumpTable(Connection conn) throws SQLException {
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT product, quantity FROM INVENTORY ORDER BY product")) {
while (rs.next()) {
System.out.printf(
"product \"%s\" - quantity: %d%n",
rs.getString("product"),
rs.getInt("quantity"));
}
}
}
In both cases we see:
Initial state:
product "one" - quantity: 123
First update:
product "one" - quantity: 123
product "two" - quantity: 234
Second update:
product "one" - quantity: 999
product "two" - quantity: 234
This is not a good way to check if a product exists because:
-There are many other things that can go wrong ( a lot of different SQLExceptions, not only PK violation ) and you will end up with a true flag.
-You should not use exceptions for something that is normal to happen.
-Throwing and catching an exception is slow.
Try this:
1) select from INVENTORY by product using count:
select count(*) from INVENTORY where product = ?
2) if the count is equal to 0 then execute the insert
else increment the quantity.

Unable to update DB by form data

please give me advice! I get form data in servlet and try to update the database, but it doesn't works. There is connection with database (without servlet code any data is properly added in db), but no any exception are thrown. The servlet get parameters - they are available in JSP by EL-expressions. I tried to update the db simply by statement, without using preparedStatement but it didn't help. Here it is the code:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBConn dbConn = new DBConn();
String number = req.getParameter("number");
String amount = req.getParameter("amount");
String date = req.getParameter("date");
ArrayList list = dbConn.returnList(number, amount, date);
req.setAttribute("attr", list);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
public class DBConn {
public ArrayList<InvoicesBean> returnList(String number, String amount, String date) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>();
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111");
statement = connection.createStatement();
preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);");
preparedStatement.setString(1, number);
preparedStatement.setString(2, amount);
preparedStatement.setString(3, date);
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("SELECT * FROM invoices;");
while (resultSet.next()){
InvoicesBean invoicesBean = new InvoicesBean();
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
beanList.add(invoicesBean);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return beanList;
}
}
InvoiceBean-class is just a standard bean class with getters/setters
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
You can not have the database column names as 'number' or 'date'. they are reserved.
check the column names again.
for checking if this is the error, you can replace the column names by column numbers 1,2,3.

Datatype mismatch for blob type blackberry

I have an exception that Datatype mismatch in this line
byte[] _data = (byte[])row.getBlobBytes(1);
and in the table I have the type of column 2 is BLOB.
public static UrlRsc getContentUrl(String name) {
UrlRsc elementRsc = null;
try {
Statement statement = DB
.createStatement("SELECT * FROM table where"
+ " Name='"
+ name + "'");
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
while (cursor.next()) {
row = cursor.getRow();
byte[]_data;
_data = row.getBlobBytes(1);
}
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
} catch (DataTypeException dte) {
System.out.println(dte.toString());
}
return elementRsc;
}
Can any one help me ?
Hi i am using following code for save image in my local database and i got success. i just posted my 3 methods
Note: When i am inserting image into data base i changed that image in byte array then only i can save into that table
1)Table creation 2) table insertion 3)image retrieving from table
ContactImage_table creation
public ContactImageTableCreation(){
try{
Statement stmt=DATABASE.createStatement("create table if not exists 'ContactImage_table'(ID 'TEXT',image 'blob',NodeId 'TEXT')");
stmt.prepare();
stmt.execute();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Insert data into ContactImage_table
public void ContactImageTableInsertion(){
try{
Statement st=DATABASE.createStatement("insert into ContactImage_table (ID,Image,NodeId)values(?,?,?)");
st.prepare();
st.bind(1, "101");
st.bind(2, BYTE_ARRY);
st.bind(3,"103");
st.execute();
st.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
Retrieving data from ContactImage_table
public ContactImageTableDataRetriving(){
try{
Statement st=DATABASE.createStatement("select * from ContactImage_table");
st.prepare();
Cursor c=st.getCursor();
Row r;
int i=0;
while(c.next()){
r=c.getRow();
i++;
// ContactImageObject is a wrapper class for data handling
contactImageObj=new ContactImageObject();
contactImageObj.setId(r.getString(0));
byte[] decoded=r.getBlobBytes(1);
EncodedImage fullImage = EncodedImage.createEncodedImage(decoded, 0, decoded.length);
Bitmap b=fullImage.getBitmap();
contactImageObj.setImage(b);
// System.out.println("Successfully retrived");
if(i==0){
// System.out.println("No Records");
}
}
st.close();
}catch (Exception e) {
// System.out.println(e.getMessage());
}
}
just cross check your code with this code snippet hope you will get resolve all the best

Object reference not set to an instance of an object ERROR

I have few textboxes whose values are to be inserted into SQl table on Submit button click. But it gives me "Object reference not set to an instance of an object" Exception. Below is the code I have written for this. Please do help me in this.
contact_new.aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime dtime;
dtime = DateTime.Now;
string ocode = offercode.Text;
string firstname = firstnamepreapp.Text;
string lastname = lastnamepreapp.Text;
string email = emailpreapp.Text;
string phoneno = phonepreapp.Text;
string timetocall = besttimepreapp.SelectedItem.Value;
string time = dtime.ToString();
//Insert the data into autoprequal table
<--- GIVES ME AN ERROR ON THIS LINE --->
Insert.insertINTOautoprequal(ocode, time, firstname, lastname, email, phoneno, timetocall);
}
Insert.cs (App_code class)
namespace InsertDataAccess
{
public class Insert
{
public Insert()
{
//
// TODO: Add constructor logic here
//
}
public static bool insertINTOautoprequal(string code, string time, string first, string last, string email, string phoneno, string timetocall)
{
bool success = false;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
conn.Open();
string query = "Insert INTO autoprequal(offercode, timeofday, firstname, lastname, emailID, phone, besttimetocall) Values(#offercode, #time, #first, #last, #email, #phoneno, #timetocall);";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
cmd.Parameters.AddWithValue("#offercode", code);
cmd.Parameters.AddWithValue("#time", time);
cmd.Parameters.AddWithValue("#first", first);
cmd.Parameters.AddWithValue("#last", last);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#timetocall", timetocall);
if (cmd.ExecuteNonQuery() == 1) success = true;
else success = false;
return success;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
}
Step through the code, as the error is most likely bubbling up from the SQL insert routine. I woulud guess the connection string is not being pulled from the configuration file, but without stepping through that is a wild guess. I would take time to learn how to debug in Visual Studio, as it will help you easily spot what cannot be a problem so you can focus on what is likely to be the problem.

Resources