【问题标题】:How can i write a public class that connect with database in netbeans?如何编写一个与 netbeans 中的数据库连接的公共类?
【发布时间】:2014-03-22 07:13:55
【问题描述】:

我必须通过 jFrame 中的上一个和下一个按钮来查看数据库的行。 所以我使用结果集方法rs.next() 和 rs.prvious() 这个代码很好,但我不知道如何为数据库连接创建一个单独的类,当 jFrame 开始运行时连接到数据库。现在我编写了整个代码创建连接并在这些按钮(前进和后退按钮)内移动前进/后退方法,因此每次我按下前进或后退按钮时,它将开始创建一个新连接并仅显示数据库的第一行。要遍历我必须首先连接数据库,我必须从这些按钮中删除数据库创建连接代码,这怎么可能?我在下面给出的前进按钮内的代码

   private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) { 

//Here each time button press it newly create a connection i want to avoid that
// I want to connect with database when jFrame start to run 
//Checking Driver

        try{
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch(Exception e)
        {
e.printStackTrace();
 }
try
{
 String s1 ="jdbc:mysql://localhost:3306/store";
 String user1="root";
 String pass="root";
 Statement stmt;
 ResultSet rs;
 Connection con;
 con=DriverManager.getConnection(s1, user1, pass);
 String q5 ="SELECT p_id,p_name,p_cata,p_brand,real_price,p_price,p_qty FROM PRODUCTS";
 stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
 rs=stmt.executeQuery(q5);
   if (rs == null)
{
 System.out.println("sorry no data");
}
if (rs!=null)
{
 if(rs.next())
{

//assigning values to strings from 
 String x0 =rs.getString("p_id");
 String x1 =rs.getString("p_name");
 String x2 =rs.getString("p_cata");
 String x3=rs.getString("p_brand");
   Float xs5=rs.getFloat("real_price");
   String x5= Float.toString(xs5);
  Float xs6=rs.getFloat("p_price");
  String x6 =Float.toString(xs6);
  int xs7 =rs.getInt("p_qty");
  String x7 =Integer.toString(xs7);
//set values to jlabel
  jLabel13.setText(x0);
  jLabel15.setText(x1);
   jLabel17.setText(x2);
  jLabel19.setText(x3);
jLabel21.setText(x5);
  jLabel23.setText(x6);
 jLabel27.setText(x7);
            }
            else{
                rs.previous();
                jLabel8.setText("End of Database");
            }
            }

}
catch(SQLException e)
{
    e.printStackTrace();
} 

【问题讨论】:

  • 您可以创建一个单独的类并在其构造函数中建立连接
  • @A5l-lE5 你能给我举个例子吗:)
  • @A5l-lE5 明白了,谢谢 :)

标签: java database netbeans database-connection resultset


【解决方案1】:

我相信您可以连接到数据库一次,将 ResultSet 数据存储在 Collection 中,每次按下后退/前进按钮时,您只显示部分您需要的收藏

关于连接方面,请查看我的代码here 以了解我所做的事情以及它是否对您有帮助。

然后,在我的主屏幕中,我只创建一个 BlahSQL 对象来处理对数据库的 SQL 查询。

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多