JDBC有关操作
一 创建数据库的连接
1 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
2 建立与数据库的连接
Connection connection=DriverManager.getConnection("jdbc:mysql://192.168.105.100:3306/educaton","username","password");
3 向数据库发送数据库操作指令,响应结果放在result 中:
Statement statement=connection.cerateStatement();
resultSet rs=statement.execteQuery("select name from student where sex="男"");
System.out.println("姓名");
4 扫描/遍历结果集:
while (rs.next())
System.out.println(rs.getString(1)+""+rs.getString(2));
5 关闭与数据库的连接
connection.close();
二 Statement 与resultSet接口的分别
如果执行的SQL是一种select类型的命令 ,则result封装Statement执行SQL命令以后所返回的数据内容,用户通过resultset 取得SQL语句返回的数据内容。
statement的方法:
close()、 addBatch(String sql)、clearBatch()、executebatch() · execute(string sql) 、 executeQuery(string sql)、 executeUpdate(string sql)、setMaxRows(int max)、 getMaxRows
resultSet的方法:
absolute(int index)、first()、last()、afterLast()、beforefirst()、next()、previous()、relative(int rows)、isAfterLast()、isbeforeFirst()、isFirst()、islast()、getRow()、getString()、getInt()、deleteRow()、refresh()、getFreshRow()、close()
statement.setMaxRows(int max):
根据传入的参数设置ResultSet对象能包含的最大行数,行数超过传入参数的ResultSet将被自动丢弃.如果传入的参数为0,则表示无限制.
statement.setFetchSize(int max):
设置从数据库取得多行的行数大小,这个方法设置的值只影响该statement.参数默认为0时,表示忽略.
三 最后也可以这样关闭与数据库的链接
finally {
ConnectionManager.closeStatement(stmt_boss);
ConnectionManager.closeStatement(stmt_local_01);
ConnectionManager.closeStatement(stmt_local_02);
ConnectionManager.closeConnection(con_boss);
ConnectionManager.closeConnection(con_local);
}
J2EE中经常将statment 简写为stmt ; resultset 简写为 rs

浙公网安备 33010602011771号