一、JDBC方式
// 加载驱动程序 Class.forName("com.mysql.jdbc.Driver"); //或 new com.mysql.jdbc.Driver(); // 创建数据库连接 String url = "jdbc:mysql://localhost:3306/blog"; String username = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url, username, password); // 创建 Statement Statement stmt = conn.createStatement(); // 读取数据 String sql = "select * from blog"; ResultSet rs = stmt.executeQuery(sql); while (rs != null && rs.next()) { String title = rs.getString(3); // 取当前行的第二列(下标从1开始) int id = rs.getInt("id"); // 根据列名获取 // byte[] bytes = rs.getBytes("..."); // 读取二进制 } // 添加数据 sql = "insert into blog values ...."; int rows = stmt.executeUpdate(sql); // 返回改动的数据的行数 // 释放资源 rs.close(); stmt.close(); conn.close();
二、Web服务器连接池方式
private static void connectionPoolHelper() { Context context = new InitialContext(); String jndi = "java:comp/env/jdbc/mysqlds"; DataSource ds = (DataSource) context.lookup(jndi); Connection conn = ds.getConnection(); //...... }
tomcat的配置:context.xml文件 <Resource name="jdbc/mysqlds" auth="Container"
type="javax.sql.DataSource" maxIdle="30" maxWait="10000"
maxActive="100" username="root" password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/blog"/>三、DBUtil方式
private static void dbutilHelper() { Context context = new InitialContext(); String jndi = "java:comp/env/jdbc/mysqlds"; DataSource ds = (DataSource) context.lookup(jndi); QueryRunner qr = new QueryRunner(ds); qr.query... qr.update... }
浙公网安备 33010602011771号