Have a error, already added a jar rs2xml.jar but when project clean and build show this error- error: cannot find symbol
jTable1.setModel(DbUtils.resultSetToTableModel(rs)); don't understand that, please help me.
private void productCodeKeyReleased(java.awt.event.KeyEvent evt) {
String tf=productCode.getText();
PreparedStatement ps = null;
ResultSet rs = null;
Result rt = null;
Connection con = getCon();
try {
if(tf.matches("^[0-9]+$")){
String query = "SELECT * FROM product WHERE ProductCode="+tf;
ps = con.prepareStatement(query);
rs=ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));//error show here
}else{
String query1 = "SELECT * FROM product WHERE ProductName LIKE'%"+tf+"%'";
ps = con.prepareStatement(query1);
rs=ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));// error show here
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(ps!=null){
rs.close();
ps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Remove
private Object DBUtils
And import instead
net.proteanit.sql.DbUtils
Related
I want to show particular data that keep one by one data in jtable, but never show all data,
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String txt = jTextField1.getText().toString();
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = Dataconnection.getConnection();
qr = "SELECT p.ProductCode,p.ProductName, p.ProductPrice FROM
customer.product p WHERE CONCAT(p.ProductCode, p.ProductName) LIKE '%"+txt+"%'";
ps=cn.prepareStatement(qr);
ps.setString(1, jTextField1.getText());
rs=ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
} catch (Exception e) {
}
}
}
I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
I have the following code:
try {
String sql = "SELECT COUNT(*) AS \"Jumlah\" FROM dokter";
ResultSet rs = connection.st.executeQuery(sql);
if(rs.next()){
abc = rs.getString("Jumlah").toString();
}
} catch (Exception e) {
System.out.println("\n Message: " + e.getMessage());
}
Why can't my ResultSet execute the given SQL?
Lose the alias, it's just an unnecessary complication. Just reference the ResultSet by the column's index:
try {
String sql = "SELECT COUNT(*) FROM dokter";
ResultSet rs = connection.st.executeQuery(sql);
if(rs.next()) {
abc = rs.getInt(1); // or getString(1) if you need it as a String
}
} catch (Exception e) {
System.out.println("\n Message: " + e.getMessage());
}
I suggest you use a PreparedStatement and a try-with-resources to close it (and your ResultSet). A count is not a String, and if you have a Connection connection then you might do something like
int count = 0;
try {
String sql = "SELECT COUNT(*) FROM dokter";
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
count = rs.getInt(1);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
I would like to be able to select a data from database and display it using the comboBox.
I have the following code but it does not display the data in the comboBox. I do realize there is codes missing to display the data and my SQL statement is not correct. I am just not sure what I can do any advise is appreciated.
try {
Statement st = db.con.createStatement();
ResultSet rs = st.executeQuery("SELECT Name, Size, Price FROM item WHERE Name=" + comboBox_1.getToolkit());
JOptionPane.showMessageDialog(frame, "displayed");
while (rs.next()) {
String name = rs.getString("Name");
String size = rs.getString("size");
String price = rs.getString("price");
textArea_Name.append(name);
textArea_size.append(size);
textArea_price.append(price);
comboBox_1.addItem(rs.getString("Name"));
comboBox_1.getSelectedItem();
}}
catch (SQLException e ) {
System.out.println("user not added");
e.printStackTrace();
}
}
});
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn= DriverManager.getConnection("jdbc:odbc:driverName");
Statement st = conn.createStatement();
ResultSet r=st.executeQuery("select * from tableName");
while (r.next()) {
JComboBox.addItem(r.getString("Key_Coloumn_Name"));
}
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
Try this tutorial. It does exactly that.
http://www.roseindia.net/tutorial/java/swing/comboboxwithdatabaseValues.html
try {
Statement stmt = db.con.createStatement();
ResultSet rs = stmt5.executeQuery("select * from tbl_your_table");
while (rs.next()) {
String pat = rs.getString("name");
jComboBox.addItem(pat);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
con = DriverManager.getConnection("jdbc:mysql://:3306/database","user","password");
stat = con.createStatement();
ResultSet rs = stat.executeQuery("select name from student;");
while(rs.next()){
jComboBox1.addItem(rs.getString("name"));
}
rs.close();
stat.close();
con.close();
comb = new JComboBox();
DefaultComboBoxModel dftm = (DefaultComboBoxModel) comb.getModel();
ArrayList<stock_data> list = userLists();
row = new Object[1];
for (int i = 0; i < list.size(); i++) {
row[0] = list.get(i).get_item();
dftm.addElement(row);
// comb.setModel(dftm);
}
Then create your method and also remember you need a stock_data Class
private ArrayList<stock_data> userLists() {
try {
connection = localhost.dbConnector();
ArrayList<stock_data> usersList = new ArrayList();
try {
String query = "Select * from itemlist";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
stock_data users;
while (rs.next()) {
// users = new stock_data(rs.getString("name"));
// usersList.add(users);
comb.addItem(rs.getString("name"));
}
rs.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "blah blah");
e.printStackTrace();
}
return usersList;
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}