【发布时间】:2021-08-18 03:02:12
【问题描述】:
我有这个程序,它由许多类组成,其中一半使用 MySQL 数据库。现在,我繁琐地为每个班级连接到 MySQL。我知道这是一个坏习惯,而且我知道这是一团糟,这就是为什么我想知道是否有办法在一堂课上一劳永逸地联系起来。不过,我不确定如何将这种连接传递给类。是和使用参数类似,还是完全不同?
如果有人想要参考,这里是我的一些课程:
import ~~~
public class LoginVerify {
public LoginVerify() {
String url = "jdbc:mysql://localhost:3306/grades";
String username = "root";
String password = "root";
JPasswordField jpf = new JPasswordField(10);
JLabel jl = new JLabel("Password: ");
jl.setFont(new Font("Times New Roman", Font.PLAIN, 15));
JTextField username1 = new JTextField(10);
JLabel label = new JLabel("Username: ");
label.setFont(new Font("Times New Roman", Font.PLAIN, 15));
final JButton okay = new JButton("Ok");
okay.setBackground(Color.WHITE);
okay.setFont(new Font("Times New Roman", Font.PLAIN, 15));
final JButton cancel = new JButton("Cancel");
cancel.setBackground(Color.WHITE);
cancel.setFont(new Font("Times New Roman", Font.PLAIN, 15));
Object[] message = {
label, username1,
jl, jpf,
};
int value = JOptionPane.showOptionDialog(
null,
message,
"LOGIN",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new Object[]{okay, cancel},
okay);
if (value == 0) {
String user = username1.getText();
char[] p = jpf.getPassword();
String pswrd = String.valueOf(p);
System.out.println("user: " + user);
System.out.println("password: " + pswrd);
// CONNECTION STARTS HERE
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "SELECT * FROM user_info WHERE user_id = ? && user_password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, user);
statement.setString(2, pswrd);
ResultSet rs = statement.executeQuery();
while(rs.next()){
String name = rs.getString("user_name");
System.out.println(name);
new UserMain(user, name, password, null);
}
ResultSet rows = statement.executeQuery();
if (!rows.next() ) {
JLabel l = new JLabel("Username or password incorrect, please try again.");
l.setFont(new Font("Times New Roman", Font.PLAIN, 15));
l.setHorizontalAlignment(SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, l, "ERROR", JOptionPane.PLAIN_MESSAGE);
new LoginVerify();
}
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
} else if (value == 1) {
JOptionPane.getRootFrame().dispose();
} else System.exit(0);
return;
}
}
【问题讨论】:
-
...是否类似于使用参数, - 是的,这就是您将对象从一个类传递到另一个类或从一个方法传递到另一个方法的方式。你为什么使用
while (rs.next)。您的查询应该只返回一个用户/密码,因此您应该使用“if 语句”。 -
@camickr 抱歉,如果这听起来缺乏知识,但是 - 你将如何传递连接?喜欢
int addNumbers (Connection con)?这行得通吗?您将如何处理 try 和 catch 异常? -
或者您可以在主类中将 Connection 设为静态变量,并在主类中添加静态方法以访问连接。