直接上代码,很简单import java.sql.*;public class BlogJdbcDemo {public static void main(String[] args) {
直接上代码,很简单
import java.sql.*;public class BlogJdbcDemo {public static void main(String[] args) { try { //initDb(); Blog blog = new Blog(); blog.setId(2); blog.setName("wen"); insertBlog( blog); blog = getBlog(1); System.out.println( blog.toString() ); } catch (Exception e) { e.printStackTrace(); } System.exit(0);}private static void insertBlog(Blog blog) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement( "INSERT INTO blog VALUES(?, ?)" ); stmt.setInt( 1, blog.getId() ); stmt.setString( 2, blog.getName() ); stmt.executeUpdate(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } }}private static Blog getBlog(int id) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = connection(); stmt = conn.prepareStatement( "SELECT id, name FROM blog WHERE id=?" ); stmt.setInt( 1, id ); rs = stmt.executeQuery(); rs.next(); Blog blog = new Blog(); blog.setId(rs.getInt(1)); blog.setName(rs.getString(2)); rs.close(); stmt.close(); return blog; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } }}private static Connection connection() throws SQLException, ClassNotFoundException { String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "0"; //Class.forName("org.h2.Driver"); //Class.forName("com.mysql.jdbc.Driver"); //Connection conn = DriverManager.getConnection( "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE", connectionProps); Connection conn = DriverManager.getConnection(url,username,password); conn.setAutoCommit( true ); return conn;}//创建数据库private static void initDb() throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement( "CREATE TABLE blog(id INT PRIMARY KEY, name VARCHAR(255)" ); stmt.executeUpdate(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } }}}