本程式主要透過ODBC連結ACCESS,故須先設計一資料庫MFG,其中Table1 欄位如下
ODBC 設定如下
主要JAVA 程式碼如下
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Login;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
/**
*
* @author jackylin
*/
public class login {
Connection Conn;
Statement st;
ResultSet rs;
JFrame f=new JFrame("Login ");
JLabel l=new JLabel("User:");
JTextField t=new JTextField(10);
JLabel l1=new JLabel("Pass:");
JTextField t1=new JTextField(10);
JButton b=new JButton("Login");
JPanel p=new JPanel();
public login()
{
connect();
frame();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new login();
System.out.print("Hello db");
}
private void connect() {
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
/*你可以使用Class的靜態forName()方法實現動態加載類別
透過java.lang.Class類別的forName()來載入並向DriverManager註冊JDBC
驅動程式(驅動程式會自動透過 DriverManager.registerDriver()方法註冊)*/
Class.forName(driver);
String db="jdbc:odbc:db1";
/*要連線資料庫,我們可以從DriverManager要求並取得Connection物件,它代表資
料庫連線物件*/
Conn=DriverManager.getConnection(db);
st=Conn.createStatement();
} catch (ClassNotFoundException | SQLException ex) {
}
}
private void frame() {
f.setSize(180,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
p.add(l);
p.add(t);
p.add(l1);
p.add(t1);
p.add(b);
f.add(p);
b.addActionListener(
new ActionListener()
{
//實作
public void actionPerformed(ActionEvent e) {
String user=t.getText().trim();
String pass=t.getText().trim();
String sql="Select * from table1 Where user='"
+user+"' and password='"+pass+"'" + "";
try
{ rs=st.executeQuery(sql);
int count=0;
while (rs.next())
{ count++;}
if (count==0) OptionPane.showMessageDialog(null,"Access denied","Login Fail",3);
}catch(Exception ex) {}
}
);
}
}
沒有留言:
張貼留言