我有两个"文件"。主程序和一个单独的类。
在课堂上我从数据库中获取一些数据并输出。现在我希望我的主文件抓取并输出表单(在文本框中)。但我不知道如何从主程序中获取变量或运行函数/类。
主:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewClass ha = new NewClass();
System.out.println(ha);
}
类别:
package kalorier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author anton.jeppsson
*/
public class NewClass {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
String server = "localhost:3306";
String password = "root";
String user = "root";
String db = "cms";
String connectionString = "jdbc:mysql://" + server + "/" + db + "?user=" + user + "&password=" + password;
System.out.println("Connecting with " + connectionString);
conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String ha = rs.getString("user_name");
System.out.println(ha);
}
}
}
答案 0 :(得分:1)
可能是这样的:
按钮actionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewClass ha = new NewClass();
for (String user : ha.doDatabaseStuff())
{
System.out.println(user);
}
}
<强>的NewClass 强>
public class NewClass {
public static void main(String[] args) {
//Maybe do other stuff here, or is this method even necessary?
}
public List<String> doDatabaseStuff() {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
String server = "localhost:3306";
String password = "root";
String user = "root";
String db = "cms";
String connectionString = "jdbc:mysql://" + server + "/" + db + "?user=" + user + "&password=" + password;
System.out.println("Connecting with " + connectionString);
conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
List<String> results = new ArrayList<>();
while (rs.next()) {
results.add(rs.getString("user_name"));
}
return results;
}
}