实验八--数据库连接

实现数据库添加、插入、删除操作:

package com.njit;

import java.awt.*;

import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import db.db;
import entity.PersonEntity;

import java.util.ArrayList;

@SuppressWarnings("serial")
public class personselect extends JFrame {
//	按钮
	private JButton b1;
	private JButton b2;
	private JButton b3;
	private JButton b4;// 查询
	private JToolBar tool;
	private JTable table;
	private MyTableModel tablemodel;
	private JTextField select;// 查询
	static String dpt;
	static JTextField dno;

	public personselect() {
		this.setSize(600, 300);
		this.setTitle("員工信息");
		this.setLocationRelativeTo(getOwner());// 居中
		// 創建組件
		tablemodel = getModel();
		table = new JTable(tablemodel); //
		table.setPreferredScrollableViewportSize(new Dimension(500, 250));
		JScrollPane scroll = new JScrollPane(table);
		getContentPane().add(scroll, BorderLayout.CENTER);

		// 添加删除修改
		b1 = new JButton(new ImageIcon("icon//WRITER.gif"));
		b1.setToolTipText("添加");
		b1.setFocusable(false);
		b1.setHorizontalTextPosition(SwingConstants.CENTER);
		b1.setVerticalTextPosition(SwingConstants.BOTTOM);
		b2 = new JButton();
		b2.setIcon(new ImageIcon("icon//UPDATE.GIF"));
		b2.setToolTipText("修改");
		b2.setFocusable(false);
		b2.setHorizontalTextPosition(SwingConstants.CENTER);
		b2.setVerticalTextPosition(SwingConstants.BOTTOM);
		b3 = new JButton(new ImageIcon("icon//DELETE.GIF"));
		b3.setToolTipText("删除");
		b3.setFocusable(false);
		b3.setHorizontalTextPosition(SwingConstants.CENTER);
		b3.setVerticalTextPosition(SwingConstants.BOTTOM);
//		查询
		b4 = new JButton();
		b4.setIcon(new ImageIcon("icon//enter.gif"));
		b4.setToolTipText("查询");
		b4.setFocusable(false);
		b4.setHorizontalTextPosition(SwingConstants.CENTER);
		b4.setVerticalTextPosition(SwingConstants.BOTTOM);
		//select = new JTextField(10);
		dno=new JTextField(10);

		tool = new JToolBar();
		tool.add(b1);
		tool.add(b2);
		tool.add(b3);
		tool.add(b4);
		tool.add(dno);
		//tool.add(select);
		tool.setRollover(true);
		getContentPane().add(tool, BorderLayout.NORTH);
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				personadd padd = new personadd();
				padd.setVisible(true);
				dispose();
			}
		});
		b2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int i, index = 0, count;
				db dbcon = new db();
				if (table.getCellEditor() != null) {
					table.getCellEditor().stopCellEditing();
				}
				try {
					String sql = "update person set name=?,sex=?," + "birthday=?,professor=?,deptno=? " + "where no=?";
					PreparedStatement presta = dbcon.PreparedStatement(sql);
					// 修改行数
					count = tablemodel.getEditedIndex().size();
					// 获得修改的行的数据,更新数据库
					if (count > 0) {
						for (i = 0; i < count; i++) {
							index = tablemodel.getEditedIndex().get(i);
							presta.setString(1, table.getValueAt(index, 1).toString());// nameSQL中(0,1,2)
							presta.setString(2, table.getValueAt(index, 2).toString());// sex在jtable中(1,2,3,4,5)
							presta.setString(3, table.getValueAt(index, 3).toString());
							presta.setString(4, table.getValueAt(index, 4).toString());
							presta.setString(5, table.getValueAt(index, 5).toString());
							presta.setString(6, table.getValueAt(index, 0).toString());
							presta.addBatch();
						}
					}
					presta.executeBatch();
				} catch (SQLException sqle) {
					System.out.println(sqle.toString());
				}
			}
		});
		b3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				db dbcon = new db();
				try {
					if (table.getSelectedRows().length > 0) {
						// 获得序列
						int[] selRowIndexs = table.getSelectedRows();
						PreparedStatement presta = dbcon.PreparedStatement("delete from person where no=?");
						for (int i = 0; i < selRowIndexs.length; i++) {
							presta.setString(1, table.getValueAt// 问题
							(tablemodel.getEditedIndex().get(i), 0).toString());
							presta.addBatch();
						}
						// 删除记录
						presta.executeBatch();
						// 重载数据JTable
						tablemodel = getModel();
						table.setModel(tablemodel);
					}
				} catch (SQLException sqle) {
					System.out.println(sqle.toString());
				}
			}
		});
		b4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dpt=dno.getText();
				select_dept view=new select_dept();
				view.setVisible(true);
				}
			});
	}

	private MyTableModel getModel() {// 連接數據庫
		MyTableModel tableModel = new MyTableModel();
		db dbcon;
		try {
			dbcon = new db();
			ResultSet rs = dbcon.executeQuery("select * from person");
			ResultSetMetaData rsmd = rs.getMetaData();
			int Colnum = rsmd.getColumnCount();
			int i;
			for (i = 1; i <= Colnum; i++)
				tableModel.addColumn(rsmd.getColumnName(i));

			ArrayList<PersonEntity> v = new ArrayList<PersonEntity>();
			while (rs.next()) {
				PersonEntity person = new PersonEntity();
				person.setNo(rs.getString("no"));
				person.setName(rs.getString("name"));
				person.setSex(rs.getString("sex"));
				person.setBrithday(rs.getDate("birthday"));
				person.setProfessor(rs.getString("professor"));
				person.setDeptno(rs.getString("deptno"));
				v.add(person);
			}
			rs.close();
			for (i = 0; i < v.size(); i++) {
				tableModel.addRow(new Object[] { v.get(i).getNo(), v.get(i).getName(), v.get(i).getSex(),
						v.get(i).getBrithday(), v.get(i).getProfessor(), v.get(i).getDeptno() });
			}
			dbcon.closeConn();
		} catch (SQLException sqle) {
			System.out.println(sqle.toString());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return tableModel;
	}

	public static void main(String[] args) {
		personselect w = new personselect();
		w.setVisible(true);
	}
}

实验八--数据库连接_第1张图片
实验八--数据库连接_第2张图片
实验八--数据库连接_第3张图片
实验八--数据库连接_第4张图片
实验八--数据库连接_第5张图片
实验八--数据库连接_第6张图片
添加代码块如下:

package com.njit;
import java.awt.*;

import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import db.db;
import java.util.ArrayList;
import entity.login_tring;
public class login_succ extends JFrame{
	private JTable table;
	private MyTableModel tablemodel;
	public login_succ() 
	{
		this.setSize(600,300);
		this.setTitle("員工信息");
		this.setLocationRelativeTo(getOwner());//居中
		//創建組件
		tablemodel = getModel();
		table = new JTable(tablemodel);		//
		table.setPreferredScrollableViewportSize(new Dimension(500,250));        JScrollPane scroll= new JScrollPane(table);getContentPane().add(scroll,BorderLayout.CENTER);
	}
	private MyTableModel getModel() 
	{//連接數據庫
		MyTableModel tableModel= new MyTableModel();
		db dbcon;
		try {   
			dbcon = new db();   
			ResultSet rs= dbcon.executeQuery("select * from \"user\"");
			ResultSetMetaData rsmd = rs.getMetaData();
			int Colnum = rsmd.getColumnCount();
			int i;
			for (i=1;i<=Colnum;i++)   
				tableModel.addColumn(rsmd.getColumnName(i));
			
			ArrayList<login_tring> v=new ArrayList<login_tring>();
			while (rs.next()) {   
				login_tring login=new login_tring();   
				login.setUname(rs.getString("Uname"));   
				login.setUpwd(rs.getString("Upwd"));   
				login.setUpower(rs.getByte("Upower"));
				v.add (login);   
				}
			rs.close();
			for (i=0;i<v.size();i++) {   
				tableModel.addRow(new Object[]{v.get(i).getUname(),
						v.get(i).getUpwd(),v.get(i).getUpower()});
				}   
			dbcon.closeConn();
			}catch (SQLException sqle) { 
				System.out.println(sqle.toString()); 
				}catch (Exception e) {
					System.out.println(e.getMessage()); 
					}
		return tableModel;}
		
	
	public static void main(String[] args) {
		login_succ w = new login_succ();
		w.setVisible(true);
	}


}

package com.njit;

import java.awt.Container;


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import db.db;
import entity.login_tring;
import com.njit.login_succ;

public class loginframe extends JFrame {
	private JTextField username;
	private JPasswordField password;
	private JButton login, register;

	public loginframe() {
		super();
		this.setSize(300, 200);
		this.setTitle("login");
		this.setLocationRelativeTo(getOwner());// 居中

//		設置組件佈局
		Container cont = getContentPane();
		cont.setLayout(new GridLayout(3, 2));

//		添加用戶密碼
		cont.add(new JLabel("username"));
		username = new JTextField(10);
		cont.add(username);
		cont.add(new JLabel("password"));
		password = new JPasswordField(10);
		cont.add(password);

//		添加登錄,註冊按鈕
		login = new JButton(new ImageIcon("icon//enter.GIF"));
		register = new JButton(new ImageIcon("icon//register.gif"));
		cont.add(login);
		cont.add(register);

//		監聽器
		login.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				db dbcon;
				dbcon = new db();
				try {
					ResultSet rs = dbcon.executeQuery("select * from \"user\"");
					ArrayList<login_tring> v = new ArrayList<login_tring>();
					while (rs.next()) {
						login_tring login = new login_tring();
						login.setUname(rs.getString("Uname"));
						login.setUpwd(rs.getString("Upwd"));
						login.setUpower(rs.getByte("Upower"));
						v.add(login);
					}
					rs.close();
					String pass = new String(password.getPassword());
					for (int i = 0; i < v.size(); i++) {
						if (username.getText().equals(v.get(i).getUname().trim())&&pass.equals(v.get(i).getUpwd().trim())) {
							System.out.println(v.get(i).getUname());
							System.out.println(v.get(i).getUpwd());
							HelloWorld hello = new HelloWorld();
							hello.setVisible(true);
							dispose();
							break;
						}
					}
					dbcon.closeConn();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
	}

	public static void main(String[] args) {
		loginframe w = new loginframe();
		w.setVisible(true);
	}
}

你可能感兴趣的:(sql)