日期:2014-05-20 浏览次数:20766 次
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.swing.JOptionPane; public class AFrame extends javax.swing.JFrame { private String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; private Connection con; // 数据库连接 public AFrame() { initComponents(); this.setTitle("连接数据库"); } // <editor-fold defaultstate="collapsed" desc=" 生成的代码 "> private void initComponents() { jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); getContentPane().setLayout(null); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().add(jTextField1); jTextField1.setBounds(60, 10, 80, 19); jLabel1.setText("IP"); getContentPane().add(jLabel1); jLabel1.setBounds(40, 10, 10, 14); jLabel2.setText("name"); getContentPane().add(jLabel2); jLabel2.setBounds(30, 30, 26, 14); getContentPane().add(jTextField2); jTextField2.setBounds(60, 30, 80, 19); jLabel3.setText("password"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 50, 46, 14); getContentPane().add(jTextField3); jTextField3.setBounds(60, 50, 80, 19); jButton1.setText("\u8fde\u63a5"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(70, 80, 55, 23); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO 将在此处添加您的处理代码: String server = this.jTextField1.getText(); String userName = this.jTextField2.getText(); String password = this.jTextField3.getText(); String url = "jdbc:jdbc:sqlserver://"+server+";DatabaseName=master"; try { Class.forName(driver); con = DriverManager.getConnection(url,userName,password); JOptionPane.showMessageDialog(this,"成功"); }catch(ClassNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this,"失败"); } catch(SQLException e) { e.printStackTrace();System.out.println(e.getMessage()); JOptionPane.showMessageDialog(this,"失败"); } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AFrame().setVisible(true); } }); } // 变量声明 - 不进行修改 private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // 变量声明结束 }