这是一个简单的注册页面。用户输入他的用户名和密码,并将其存储在数据库中。
问题是它没有将数据存储在数据库中。为了测试目的,我做了一个主要的方法,它工作得很好,但从小程序来看却没有。虽然它没有给我任何错误。
顺便说一句,我添加了 MySQL Java 连接器。
我知道直接将小程序与 MySQL 连接是一个坏主意,但我这样做是为了学校作业。我在网上寻找了大部分可用的资源,但我找不到答案。
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DBConnect
{
public DBConnect(){
}
public String getCon(String name, String password) {
Connection con = null;
PreparedStatement pst = null;
String ur1 = "jdbc:mysql://localhost/test";
String user = "root";
String pass = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(ur1, user, pass);
pst =con.prepareStatement("INSERT INTO persons (name, password) VALUES (?,?)");
pst.setString(1, name);
pst.setString(2, password);
pst.executeUpdate();
} catch (Exception ex) {
Logger lgr = Logger.getLogger(DBConnect.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DBConnect.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
return name;
}
}
import java.sql.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import javax.swing.JOptionPane;
public class Table extends JApplet implements ActionListener
{
TextField username, password;
public String s1,s2,s;
String msg ="";
private Thread th;
Button submit;
Label LabelName, LabelPass;
DBConnect connect = new DBConnect();
public Table(){
}
public void init()
{
setLayout(null);
username = new TextField(8);
password = new TextField(8);
submit = new Button ("Register");
LabelName = new Label("User Name");
LabelPass = new Label("Password");
username.setBounds(100,40,80,20);
password.setBounds(100,80,80,20);
submit.setBounds(40,110,80,30);
LabelName.setBounds(20,40,80,20);
LabelPass.setBounds(20,80,80,20);
add(LabelName);
add(username);
add(LabelPass);
add(password);
add(submit);
submit.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString(s1,100,275); // just for a test purpose
g.drawString(s2,100,300); // just for a test purpose
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == submit) {
try
{
s1 = username.getText();
s2 = password.getText();
repaint();
connect.getCon(s1, s2); // here is the problem
JOptionPane.showMessageDialog(null, "you're registered");
}
catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Something Wrong / This user name already exists");
}
}
}
public String getS1(){
return s1;
}
public String getS2(){
return s2;
}
}