首页 > 代码库 > JDBC简单范例
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-----"); } }}
JDBC简单范例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。