下载连接驱动
安装完oracle之后 D:appAdministratorproduct11.2.0dbhome_1jdbclib 目录下拷贝
支持jdk1.6以上
From.java
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.sql.SQLException; public class From extends JFrame { private JPanel jPanel; private JButton button1; private JButton button2; private JTextField jTextField; From() { init(); } public static void main(String[] args) { JFrame frame = new JFrame("From"); frame.setContentPane(new From().jPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setSize(600, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); } private void init() { Button1ClickListener buttonClickListener1 = new Button1ClickListener(); Button2ClickListener buttonClickListener2 = new Button2ClickListener(); button1 = new JButton("增删改"); button2 = new JButton("查询"); jTextField = new JTextField(10); jPanel.add(button1); jPanel.add(button2); jPanel.add(jTextField); button1.addActionListener(buttonClickListener1); button2.addActionListener(buttonClickListener2); } //增删改监听 class Button1ClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { ConnOracle connOracle = new ConnOracle(); int count = connOracle.insert(); if (count != 0) { JOptionPane.showMessageDialog(null, "连接成功更改" + count + "行数据", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "数据异常", "提示", JOptionPane.ERROR_MESSAGE); } } } //查询监听 class Button2ClickListener implements ActionListener { String str; public void actionPerformed(ActionEvent e) { ConnOracle connOracle = new ConnOracle(); ResultSet rs = connOracle.query(); try { if (rs != null) { while (rs.next()) { jTextField.setText(rs.getString(1)); String str = rs.getString("name"); } } else { JOptionPane.showMessageDialog(null, "数据异常", "提示", JOptionPane.ERROR_MESSAGE); } } catch (SQLException e1) { e1.printStackTrace(); } } } }
ConnOracle.java
import java.sql.*; public class ConnOracle { private static String user = "MES"; private static String password = "zidonghua"; private static String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; // 创建一个数据库连接 Connection connection = null; // 创建预编译语句对象,一般都是用这个而不用Statement Statement pstm = null; // 创建一个结果集对象 ResultSet rs = null; //插入,更新,删除 public int insert() { int count=0; String str = "insert into FRUITS (ID,NAME,PLACE,AMOUNT) values(6,'土豆','山东',99)"; try { connection = DriverManager.getConnection(url, user, password); pstm = connection.createStatement(); count = pstm.executeUpdate(str); } catch (SQLException e) { e.printStackTrace(); } return count; } //查询 public ResultSet query() { ResultSet rs=null; String str = "select NAME from FRUITS where id=8"; try { connection = DriverManager.getConnection(url, user, password); pstm = connection.createStatement(); rs = pstm.executeQuery(str); } catch (SQLException e) { e.printStackTrace(); } return rs; } }