神刀安全网

JDBC(PreparedStatement)

http://www.stormxing.com/posts/jdbcpre

JDBC连接流程

JDBC(PreparedStatement)

JDBC基础

1、新建测试类JdbcTest

package jdbc;  import org.junit.Test; import utils.JdbcUtil;  import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;  public class JdbcTest {      @Test     public void testInsert() {         ResultSet rs = null;         Connection conn = null;         PreparedStatement stmt = null;          try {             //1、通过工具类获取连接对象             conn = JdbcUtil.getConnection();             //2、准备预编译的sql             String sql = "SELECT  * FROM student";             //3、执行预编译的sql语句             stmt = conn.prepareStatement(sql);             //4、设置参数值 //            stmt.setString(1, "张三"); //            stmt.setInt(1, 2);             //5、发送参数,执行sql             rs = stmt.executeQuery();             while (rs.next()){                 int id = rs.getInt("id");                 String name = rs.getString("name");                 String gender = rs.getString("gender");                 System.out.println(id+","+name+","+gender);             }         } catch (SQLException e) {             e.printStackTrace();         } finally {             JdbcUtil.close(rs,stmt, conn);         }     } } 

2、创建工具类JdbcUtil

package utils;  import java.sql.*;  public class JdbcUtil {      //静态代码块(只加载一次)     static {         try {             Class.forName("com.mysql.jdbc.Driver");         } catch (ClassNotFoundException e) {             e.printStackTrace();             System.out.println("驱动程序注册出错");         }     }      //抽取获取连接对象的方法     public static Connection getConnection() {         Connection conn = null;          try {             String url = "jdbc:mysql://localhost:3306/javaee?useUnicode=true&characterEncoding=utf-8";             String user = "root";             String password = "root";             conn = DriverManager.getConnection(url, user, password);             if (conn != null) {                 System.out.println("数据库连接成功!");             }         } catch (SQLException e) {             e.printStackTrace();             System.out.println("数据库连接失败!");         }          return conn;     }      //抽取释放资源的方法     public static void close(ResultSet rs, Statement stmt, Connection conn) {         try {             rs.close();             stmt.close();             conn.close();         } catch (SQLException e) {             e.printStackTrace();         }         System.out.print("关闭成功");     }  }  

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » JDBC(PreparedStatement)

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址