• JDBC简单范例


    连接工具类

    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBUtil {
        // 建立连接方法
        public static Connection open() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                return DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/GeekDB", "root", "123456");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        // 关闭连接方法
        public static void close(Connection conn) {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
        }
    
    }

    使用范例

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Test {
    
        public static void main(String[] args) {
    
            Connection conn = null;
            String sql = null;
            Statement stmt = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
    
            // Statement查询*
            sql = "select * from customertbl";
            conn = DBUtil.open();
            try {
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String email = rs.getString(3);
                    System.out.println(id + " " + name + " " + email);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DBUtil.close(conn);
                System.out.println("-----DONE-----");
            }
    
            // PreparedStatement插入一条
            sql = "insert into customertbl (name, email) values (?, ?)";
            conn = DBUtil.open();
            try {
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, "Amy");
                pstmt.setString(2, "amy@163.com");
                pstmt.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DBUtil.close(conn);
                System.out.println("-----DONE-----");
            }
    
        }
    }
  • 相关阅读:
    【CYH-02】noip2018数论模拟赛:赛后题解
    C语言 malloc函数
    C 库函数
    C语言strcmp()函数:比较两个字符串
    C语言sprintf函数的深入理解
    C语言strcat()函数:字符串连接(拼接)
    liunx 中设置zookeeper 自启动(service zookeeper does not support chkconfig)
    页面上出现403错误,并解决
    Mac 下安装nginx
    nginx: [emerg] unknown directive "," in /usr/local/etc/nginx/nginx.conf:80
  • 原文地址:https://www.cnblogs.com/yangleda/p/4224791.html
Copyright © 2020-2023  润新知