JDBC连接Mysql实现基本查询
- 在MySQL数据库中建立databaseweb数据库,并创建一张tb_person表;
- 新建Web Project——datebaseWeb,把MySQL的JDBC驱动加到项目classpath目录下;
-
新建listPerson.jsp,实现JDBC访问数据库的步骤如下:
1.注册数据库驱动:
DriverManager.registerDriver(new Driver());
2.获取数据库连接:conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseweb","root","root");
3.获取Statement:
stmt = conn.createStatement();
4.获取查询结果,以ResultSet返回:rs = stmt.executeQuery("select * from tb_person");
5.获取表项数据:while(rs.next()) { int id = rs.getInt("id"); int age = rs.getInt("age"); ...... }
Statement批处理SQL
使用statement进行批处理SQL的基本步骤:
1.new Driver();
2.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseweb","root","root");
3.stmt = conn.createStatement();
4.for(int i = 0;i < 5;i++)
{
String sql = ""; (拼凑sql语句)
stmt.addBatch(sql); 批量添加
}
5.int[] result = stmt.executeBatch(); 返回受影响行数数组
PreparedStatement 批处理SQL
使用PreparedStatement进行批处理SQL的基本步骤:
1.new Driver();
2.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseweb","root","root");
3.preStmt = conn.prepareStatement("insert into tb"+"(name,age)"+"value(?,?)");
4.for(int i =0;i < 5;i++)
{
int index = 1;
preStmt.setString(index++,"Name"+i); 第一个参数
preStmt.setInt(index++,25); 第二个参数
preStmt.addBatch(); 添加同一条带参数的SQL语句
}
5.int[] result = stmt.executeBatch();