JDBC数据库连接的简单应用

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author student
 */
public class PhoneBook1 extends javax.swing.JFrame {

    /**
     * Creates new form PhoneBook
     */
    public PhoneBook1() {
        initComponents();
        new Dao();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("OK");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton1MouseReleased(evt);
            }
        });

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel1.setText("姓名");

        jLabel2.setText("手机号");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(62, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(88, 88, 88))
            .addGroup(layout.createSequentialGroup()
                .addGap(107, 107, 107)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(52, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {                                      
        String name=jTextField1.getText();
        //System.out.println("name = " + name);
        String PhoneNum = Dao.getPhoneNum(name);
     //   System.out.println("phoneNum = "+ PhoneNum);
        jTextField2.setText(PhoneNum);
//        this.setVisible(false);
        //new child1()
        // TODO add your handling code here:
    }                                     

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PhoneBook1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PhoneBook1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PhoneBook1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PhoneBook1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PhoneBook1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                  
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Samuel
 */
/*数据库操作类*/
public class Dao {

    protected static String dbClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    //注意修改数据库名称
    protected static String dbUrl = "jdbc:sqlserver://localhost:1434;DatabaseName=PhoneBook";
    //数据库用户名保存在变量dbUser中
    protected static String dbUser = "sa";
    //数据库密码保存在dbPwd中
    protected static String dbPwd = "123456";
    protected static String second = null;
    private static Connection conn = null;
    //Dao类的构造方法
    Dao() {
        try {
            if (conn == null) {
                Class.forName(dbClassName);
                conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
            } else {
                return;
            }
            System.out.println("conn成功!");//控制台打印显示连接成功
        } catch (Exception ee) {
            ee.printStackTrace();
        }

    }
    /*数据库查询方法
    * 方法参数:sql查询语句
    * 返回值:查询返回的结果集
    */
    private static ResultSet executeQuery(String sql) {
        try {
            if (conn == null) {
                new Dao();
            }
            //下面一行调用了Statement类的executeQuery(String sql)方法
            //执行给定的 SQL 语句,该语句返回单个 ResultSet 对象,绝大多数是用SELECT语句
            return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
        }
    }
    /*数据库更新方法
    * 方法参数:sql更新语句
    * 返回值:一个整数,指示受影响的行数(即更新计数)
    */
    private static int executeUpdate(String sql) {

        try {
            if (conn == null) {
                new Dao();
            }
            //下面一行调用了Statement类中的executeUpdate方法
            //用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句
            return conn.createStatement().executeUpdate(sql);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            return -1;
        } finally {
        }
    }
/**************************下面是针对当前项目定义的方法*************************************/
    public static boolean loginResult(String name, String password) {
        //在当前数据库中的User_Info表中查询
        String sql = "select *  from User_Info where name='" + name
                + "' and password='" + password + "'";
        //返回的结果,包括所有的用户密码(name和password)注册信息
        ResultSet rs = Dao.executeQuery(sql);
        boolean loginR = false;
        try {
            //从当前结果集rs中取得需要的信息,并进行比较核对
            while (rs.next()) {
                String nameGet = rs.getString("name");
                String passwordGet = rs.getString("password");
                if (nameGet.equals(name) && passwordGet.equals(password)) {
                    loginR = true;
                    break;//跳出当前循环
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
        }
        Dao.close();
        return loginR;
    }
  
   
    public static String getPhoneNum(String name) {
        //在当前数据库中的Phone表中查询
        String sql = "select *  from phone where name='" + name
                + "' ";
        //返回的结果,包括所有的用户注册信息
        ResultSet rs = Dao.executeQuery(sql);
        String strResult=null;
        try {
            //从当前结果集rs中取得需要的信息,并进行比较核对
            while (rs.next()) {
               strResult = rs.getString("phone");
              
            }
        } catch (SQLException ex) {
            Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
        }
        Dao.close();
        return strResult;
    }
/************************记得关闭连接通道*************************************/
    public static void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDBC 连接数据库的过程一般包括以下步骤: 1. 加载数据库驱动程序:使用 Class 类的 forName() 方法加载 JDBC 驱动程序,例如: ``` Class.forName("com.mysql.jdbc.Driver"); ``` 2. 建立数据库连接:使用 DriverManager 类的 getConnection() 方法建立与数据库的连接,需要指定数据库的 URL、用户名和密码,例如: ``` String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "mypassword"; Connection conn = DriverManager.getConnection(url, username, password); ``` 其中,"jdbc:mysql://" 表示连接的是 MySQL 数据库,"localhost:3306" 表示连接的是本地主机上的 MySQL 数据库,"mydatabase" 是数据库的名称,"root" 是数据库的用户名,"mypassword" 是数据库的密码。 3. 创建 Statement 对象:通过 Connection 对象的 createStatement() 方法创建 Statement 对象,用于执行 SQL 语句,例如: ``` Statement stmt = conn.createStatement(); ``` 4. 执行 SQL 语句:使用 Statement 对象的 execute() 方法执行 SQL 语句,例如: ``` String sql = "SELECT * FROM users"; ResultSet rs = stmt.execute(sql); ``` 5. 处理结果集:通过 ResultSet 对象处理查询结果,例如: ``` while (rs.next()) { String username = rs.getString("username"); String password = rs.getString("password"); // 处理查询结果 } ``` 6. 关闭数据库连接:使用 Connection 对象的 close() 方法关闭数据库连接,例如: ``` conn.close(); ``` 在实际应用中,还需要考虑异常处理、事务处理等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值