这可能会帮助你
import java.sql.*;
import java.math.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
/* 与 MS-Access 的数据库连接是通过在此示例中创建 DataSourceName(dsn) 完成的*/ /* 使用此示例的步骤:
lblname = new JLabel("名称:"); lbladd = new JLabel("地址:"); lblmsg = new JLabel("",JLabel.CENTER);
//initializing panels
p1 = 新的 JPanel(); p2 = 新的 JPanel(); p3 = 新的 JPanel(); psouth = 新的 JPanel();
//adding buttons and label to panel p1
//setting flowlayout
p1.setLayout(new FlowLayout());
p1.add(btnok); p1.add(btnexit); p1.add(btnaddnew); //将 lblmsg 添加到面板 p3 p3.add(lblmsg);
//adding both the panels to new panel,psouth
//settin layout 2:1
psouth.setLayout(new GridLayout(2,1));
psouth.add(p3);
psouth.add(p1);
//adding label and textfields to panel p2
p2.setLayout(new GridLayout(3,1)); //设置面板p2的线条和标题边框 p2.setBorder(BorderFactory.createLineBorder(Color.red)); p2.setBorder(BorderFactory.createTitledBorder("输入您的详细信息")); p2.add(lblname); p2.add(tf1); p2.add(lbladd); p2.add(tf2);
//adding panel to container
this.getContentPane().add(p2,"Center");
this.getContentPane().add(psouth,"South");
this.setSize(300,300);
this.setLocation(100,200);
this.show();
}
public static void main(String args[])
{
AddNewStudent ad = new AddNewStudent();
}
//事件处理
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btnok)
{
PreparedStatement pstm;
ResultSet rs;
String sql;
//if no entries has been made and hit ok button throw an error
//you can do this step using try clause as well
if((tf1.getText().equals("")&&(tf2.getText().equals("")))) { lblmsg.setText("输入您的详细信息"); lblmsg.setForeground(Color.magenta); }
别的 {
try { //加载驱动 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//connection object created using DriverManager class
//student_base is the name of the database
Connection connect =
DriverManager.getConnection("jdbc:odbc:student_base");
//creating prepared statement object pstm so that query can be
发送到数据库
pstm=connect.prepareStatement("insert into student_base
values(?,?)");
pstm.setString(1,tf1.getText());
pstm.setString(2,tf2.getText());
//execute method to execute the query
pstm.executeUpdate();
lblmsg.setText("Details have been added to database");
//closing the prepared statement and connection object
pstm.close();
connect.close();
} catch(SQLException sqe) { System.out.println("SQl 错误"); } catch(ClassNotFoundException cnf) { System.out.println("找不到类错误"); } } } //点击按钮添加新,你的文本框将是空的输入
next record
if(e.getSource()==btnaddnew)
{
tf1.setText("");
tf2.setText("");
}
if(e.getSource()==btnexit)
{
System.exit(1);
}
}
}