I refer this first and edited like this..same combobox name.but when I call this method it ask for a keyEvent..for that what should I do.and is there any wrong with this code
ResultSet rset;
public void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)ComboItemName.getEditor().getEditorComponent()).getText();
try {
rset = new JDBC.DB().getData("SELECT * FROM item_reg WHERE id = '"+sch+"'");
} catch (Exception e) {
System.out.println(e);
}
ComboItemName.removeAllItems();
try {
while (rset.next()) {
String item = rset.getString("id");
ComboItemName.addItem(item);
}
} catch (SQLException ex) {
System.out.println(ex);
//Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
ComboItemName.setSelectedItem(null);
ComboItemName.setPopupVisible(true);
((JTextField)ComboItemName.getEditor().getEditorComponent()).setText(sch);
}
Related
I am currently learning socket programming in java. I have tried to create some basic application which worked pretty well. Now, I am trying to do a client/Server application with jdbc. However, I am facing some issues in the clientside. I have a Jpanel which has a Jbutton add product and delete product and also in this panel I have a Jtable that shows all the products present in the database. I am using Object streams to allow data to be transferred. The problem is that when an operation(add,delete,show) has already been done I can't use the ObjectOutputStream again to undergo another operation. The Jpanel panel freezes without giving any error. I have flushed all the output Streams an yet the problem is still here. But when an operation runs for the first time it runs successfully, i assume that all code for the operations are running well. I would really appreciate some help please. Sorry for not putting the naming rules.
Thank you.
Server
public class Serverframe extends javax.swing.JFrame
/**
* Creates new form Serverframe
*/
ObjectOutputStream toClientO;
ObjectInputStream fromClientO;
Socket clientconnection=null;
Socket request;
Socket reqOperation;
Connection con =null;
public Serverframe() throws IOException {
initComponents();
con=DBconnnection.conn();
}
private void btnstartActionPerformed(java.awt.event.ActionEvent evt) {
try {
btnstart.setEnabled(false);
btnstart.setVisible(false);
btnstop.setVisible(true);
btnstop.setEnabled(true);
Serverside();
} catch (IOException ex) {
Logger.getLogger(Serverframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnstopActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
btnstart.setVisible(true);
btnstart.setEnabled(true);
btnstop.setVisible(false);
btnstop.setEnabled(false);
}
public void Serverside() throws IOException{
try{
int serverport = 1234;
ServerSocket serversocket = new ServerSocket(serverport);
// System.out.println("server is now ready....");
txtshowtext.append("server is now ready....");
while(true){
Socket clientconnection=serversocket.accept(); /*waiting for clients to connect*/
Thread t=new Thread(new clienthandler(clientconnection));
t.start();
}
}
catch(IOException ioe)
{
System.out.println("error");
txtshowtext.append("error");
}
}/*end of constructor*/
class clienthandler implements Runnable
{
public clienthandler( Socket clientconnection)
{
try{
request = clientconnection;
fromClientO=new ObjectInputStream (request.getInputStream( ));
toClientO=new ObjectOutputStream( request.getOutputStream());
}catch(IOException io)
{
System.out.println("can't take i/o stream");
txtshowtext.append("can't take i/o stream");
}
}
#Override
public void run( )
{
String firstname = null;
String lastname = null;
String phone = null;
String email = null;
String address = null;
String username = null;
String password = null;
String test1="";
PreparedStatement pst = null;
PreparedStatement ps = null;
ResultSet rst=null;
ResultSet rs=null;
String user=null;
String pass=null;
String Product = null;
String Brand = null;
String Model = null;
String Price = null;
String Stock = null;
String Features = null;
String Category = null;
String PhotoPath = null;
Statement statement=null;
try {
test1=(String)fromClientO.readObject();
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
// **********************************ADD PRODUCT*********************************
if(test1.equals("addproduct"))
{ ArrayList<String> product=new ArrayList<>();
try {
Object o=new Object();
o=fromClientO.readObject();
product=(ArrayList<String>) o;
Product = product.get(0);
Brand = product.get(1);
Model = product.get(2);
Price = product.get(3);
Stock = product.get(4);
Features = product.get(5);
Category = product.get(6);
PhotoPath = product.get(7);
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
try {
String sql1="insert into PRODUCT(Product,Brand,Model,Price,Stock,Features,Category_Id,imagepath) values(?,?,?,?,?,?,?,?)";
pst=con.prepareStatement(sql1);
pst.setString(1,Product);
pst.setString(2,Brand);
pst.setString(3,Model);
pst.setInt(4,Integer.parseInt(Price));
pst.setInt(5,Integer.parseInt(Stock));
pst.setString(6,Features);
pst.setInt(7,Integer.parseInt(Category));
pst.setString(8,PhotoPath);
pst.execute();
toClientO.writeObject(1);
toClientO.flush();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
finally{
try{
pst.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
//SHOW PRODUCTS
if(test1.equals("showproducts"))
{
try{
ArrayList<Product> productList = new ArrayList<>();
String query1 = "SELECT * FROM Product";
statement =con.createStatement();
rs = statement.executeQuery(query1);
Product product;
while(rs.next()){
product =new Product(rs.getInt("Product_Id"), rs.getString("Product"), rs.getString("Brand"),rs.getString("Model"),rs.getString("Features"), rs.getInt("Stock"),rs.getInt("Price"), rs.getInt("Category_Id"),rs.getString("imagepath"));
productList.add(product);
}
toClientO.writeObject(productList);
toClientO.flush();
}catch(Exception ex){
ex.printStackTrace();
}
finally{
try {
statement.close();
// toClientO.flush();
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
//DELETE PRODUCTS
if(test1.equals("delproducts")){
try{
int value = Integer.parseInt((String)fromClientO.readObject());
String query= "DELETE FROM Product WHERE Product_Id =?";
pst = con.prepareStatement(query);
pst.setInt(1,value);
pst.execute();
toClientO.writeObject(1);
toClientO.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
try {
pst.close();
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
**ClIENT**
public void adminside(){
try{
socket=new Socket("localhost", 1234); /*making connection*/
toServerO= new ObjectOutputStream( socket.getOutputStream());
fromServerO= new ObjectInputStream (socket.getInputStream( ));
System.out.println("Connection Successful");
}catch(IOException ioe)
{
ioe.printStackTrace();
System.out.println("can't connect");
}
}
****************************ADD PRODUCTS*******************
private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtproduct.getText().isEmpty() || txtbrand.getText().isEmpty() || txtmodel.getText().isEmpty() || txtprice.getText().isEmpty() || txtquantity.getText().isEmpty() || txtfeatures.getText().isEmpty() || combocategory.getSelectedIndex() == 0){
JOptionPane.showMessageDialog(rootPane, "Required Fields are not Filled", "Fields are Empty",1);}
else{
try {
toServerO.writeObject("addproduct");
ArrayList<String> product=new ArrayList<>();
product.add(txtproduct.getText().trim());
product.add(txtbrand.getText().trim());
product.add(txtmodel.getText().trim());
product.add(txtprice.getText().trim());
product.add(txtquantity.getText().trim());
product.add(txtfeatures.getText().trim());
product.add(String.valueOf(combocategory.getSelectedIndex()));
product.add(txtphotopath.getText().trim());
toServerO.writeObject(product);
toServerO.flush();
int st=0;
try {
st=(int)fromServerO.readObject();
} catch (IOException | ClassNotFoundException ex) {
// Logger.getLogger(Login_JFrame.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
if(st==1){
JOptionPane.showMessageDialog(rootPane, "Product Successfully Added", "Success",1);
resetAdd();
}
else{
JOptionPane.showMessageDialog(rootPane, "An Error Has Occured, Please Try Again...", "Error",1);
}
} catch (IOException ex) {
// Logger.getLogger(SignUp_JFrame.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
//********************Delete Product****************************
private void delEntryActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
toServerO.writeObject("delproducts");
toServerO.flush();
if(txtprodId.getText().isEmpty()){
JOptionPane.showMessageDialog(rootPane, "Select a Record First", "Field is Empty",1);
}
else{
try{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Do You Really Want to Delete this Record?", "Delete Product", dialogButton);
if(dialogResult == 0) {
try{
String value = txtprodId.getText().trim();
toServerO.writeObject(value);
toServerO.flush();
int st=0;
try {
st=(int)fromServerO.readObject();
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
if(st==1){
DefaultTableModel model = (DefaultTableModel)tblproducts.getModel();
model.setRowCount(0);
// show_products();
reset();
JOptionPane.showMessageDialog(rootPane, "Record successfully deleted", "Deleted",1);
}
else{
JOptionPane.showMessageDialog(rootPane, "An Error took Place", "Error",1);
}
}catch(HeadlessException ex){
ex.printStackTrace();
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}catch(IOException ex){
ex.printStackTrace();
}
}
//******************** Show Products*************
public ArrayList<Product> pList(){
ArrayList<Product> productList=new ArrayList<>();
try {
Object o=new Object();
o=fromServerO.readObject();
productList=(ArrayList<Product>) o;
} catch (Exception ex) {
ex.printStackTrace();
}
return productList;
}
public void show_products() throws IOException{
try{
toServerO.writeObject("showproducts");
toServerO.flush();
}catch(IOException ex){
ex.printStackTrace();
}
ArrayList<Product> list = pList();
DefaultTableModel model = (DefaultTableModel)tblproducts.getModel();
Object[] row = new Object[9];
model.setRowCount(0);
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getproductId();
row[1]=list.get(i).getproduct();
row[2]=list.get(i).getbrand();
row[3]=list.get(i).getmodel();
row[4]=list.get(i).getfeatures();
row[5]=list.get(i).getstock();
row[6]=list.get(i).getprice();
row[8]=list.get(i).getcatId();
row[7]=list.get(i).getimagepath();
model.addRow(row);
}
}
}
}
I'm seeking how to execute ActionPerformed on the first combobox in order to filter the next one. This is based on Mysql.
I'm using the following codes to fill the first combo, which is working fine
Vector<String> comboBoxItems = new Vector<String>();
final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(comboBoxItems);
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
PreparedStatement st1 = null;
ResultSet rs1=null;
String strPro = "";
String sql1 ="select distinct T_AdressePro from t_adresse order by T_AdressePro";
try {
st1= MconnectionDB.con.prepareStatement(sql1);
rs1 = st1.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs1.next()){
strPro =rs1.getString("T_AdressePro");
comboBoxItems.add(strPro);
comboBoxPro= new JComboBox<String>(model);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs1.close();
st1.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
And then, I'm adding another similar code in ActionPerformed on the first combo to filter the second one:
comboBoxPro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector<String> comboBoxItemsC = new Vector<String>();
final DefaultComboBoxModel<String> modelC = new DefaultComboBoxModel<String>(comboBoxItemsC);
String strCir = "";
PreparedStatement st2 = null;
ResultSet rs2=null;
String sql2 ="select distinct T_AdresseCir from t_adresse where T_AdressePro=? order by T_AdresseCir";
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
comboBoxPro.getSelectedItem();
strProCombo = comboBoxPro.getSelectedItem().toString();
System.out.println(strProCombo);
try {
st2= MconnectionDB.con.prepareStatement(sql2);
st2.setString(1, strProCombo); //strProCombo
rs2 = st2.executeQuery();
}catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs2.next()){
System.out.println(rs2.getString("T_AdresseCir"));
strCir =rs2.getString("T_AdresseCir");
comboBoxItemsC.add(strCir);
comboBoxCir= new JComboBox<String>(modelC);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs2.close();
st2.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
});
I'm noticing that the follogwing code "System.out.println(rs2.getString("T_AdresseCir"));" is returning the expected result but not the combobox. Still empty. Your support please, thanks.
In your actionPerformed method you are creating new JComboBox but you don't add it to gui. That is probably why you can't see its contents. You should instead create new ComboBoxModel and set it on existing JComboBox. You should probably use try with resources too to make your code more readable.
Pseudo code (I don't have your database):
// create new model for your comboBox
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
// fill model with data
try (Connection con = /*get connection to your db by any means necessary*/;
PreparedStatement stmt = con.prepareStatement(/*your query*/);
ResultSet rs = stmt.executeQuery();) {
while (rs.next()) {
model.addElement(rs.getString(/*your column*/));
}
comboBox.setModel(model); // set model for your JComboBox
} /*catch and all that*/
// no need for finally because try-with-resources.
I have got a method with prepared statement that works with Connection class. How to make that i could work with Hibernate sessions?
#SuppressWarnings("unchecked")
#Override
public List<Users> listUsersSort(int weight, String gender, String place, int ageTo, String currentUser) {
System.out.println(weight+gender+place+ageTo+currentUser);
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
int iterator=0;
List<Users> usersList =null;
String selectSQL="select users.username, users.checkusr, users.password, users.name, users.enabled, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place, users.photo from users where users.enabled = true";
System.out.println(selectSQL);
try {
dbConnection.prepareStatement(selectSQL);
} catch (SQLException e) {
System.out.println("first catch block");
e.printStackTrace();
}
if (weight<40 == false) {
String weightParam = " AND users.weight <= ?";
selectSQL=selectSQL.concat(weightParam);
System.out.println(selectSQL);
try {
preparedStatement.setInt(iterator++, weight);
} catch (SQLException e) {
System.out.println("second catch block");
e.printStackTrace();
}
System.out.println(selectSQL);
}
if (gender.isEmpty() == false) {
String genderParam = " AND users.gender LIKE '?'";
selectSQL=selectSQL.concat(genderParam);
try {
preparedStatement.setString(iterator++, gender);
} catch (SQLException e) {
e.printStackTrace();
}
}
if (place.isEmpty() == false) {
String placeParam = " AND users.place LIKE '?'";
selectSQL=selectSQL.concat(placeParam);
try {
preparedStatement.setString(iterator++, place);
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ageTo<40 == false) {
String age = " AND users.age <= ?";
selectSQL=selectSQL.concat(age);
try {
preparedStatement.setInt(iterator++, ageTo);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String withoutUser=" AND users.username NOT LIKE '?'";
selectSQL=selectSQL.concat(withoutUser);
try {
preparedStatement.setString(iterator++, currentUser);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("FINAL QUERY IS: " + selectSQL);
ResultSet rs=null;
try {
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (rs.next()) {
String username = rs.getString("username");
System.out.println("username : " + username);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usersList;
}
The best way to achieve this with Hibernate is to use native queries. For example, if you're using the Session interface:
SQLQuery sqlQuery = session.createSQLQuery(selectSQL);
After reading through a lot of similar questions I have not been able to get a solution that works for me.
I have this methods:
In a crawler4j Controller I do this:
ArrayList<String> urls = Urls.getURLs(100);
for (String s : urls) {
System.out.println("Adding URL: " + s);
controller.addSeed(s);
}
this is getURLs():
public static ArrayList<String> getURLs(int number) {
ArrayList<String> list = new ArrayList<String>();
String getStatement = "select * from " + Configurations.getStringProperty("mysql.urls.db_name", "urls") + " where retrieved=0 limit "
+ Configurations.getStringProperty("mysql.urls.limit", "100") + ";";
ResultSet rs;
rs = Databaseclient.executeStatement(getStatement);
try {
while (rs.next()) {
list.add(rs.getString("url"));
// Databaseclient.executeStatement("update urls set retrieved = true where id = "
// + rs.getInt("id") + ";");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
This is my executeStatement():
public static ResultSet executeStatement(String s) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// fetch a connection
connection = DataSource.getInstance().getConnection();
if (connection != null) {
statement = connection.createStatement();
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
}
return resultSet;
}
I get the error
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:997)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:983)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:928)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:799)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6982)
at database.Urls.getURLs(Urls.java:27)
at crawler.Controller.main(Controller.java:53)
Which is the line
while (rs.next()) {
in my getURLs() method.
What am I doing wrong? There is no code between getting the statement and the while loop that could close the statement.
Your code is a bit off, but if I understand you then don't close your ResultSet in the finally block of your executeStatement method.
public static ResultSet executeStatement(Connection connection,
Statement statement, String s) {
ResultSet resultSet = null;
try {
if (statement != null) {
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
}
return resultSet;
}
Then you need to pass in a Connection and Statement, and you'll get a ResultSet back. Also, the caller should then close all three when it's done with the ResultSet.
i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}