JDBC常用接口
1、驱动程序接口Driver
创建驱动类的实例,java.lang.Class的静态方法forName加载此类
2、驱动程序管理器DriverManager
管理驱动程序,并在数据库和驱动程序建立连接
3、数据库连接接口Connection
连接特定的数据库
4、静态sql语句执行接口Statement
executeUpdate()返回int的更新条数
executeQuery()返回ResultSet实例
execute()
5、ResultSet处理结果集
>读取:(列名/列号)
rs.getString("username")
rs.getString(1)
next()
>滚动结果集
conn.createStatement(type,concurrency)
type:结果集是否滚动
concurrency:是否更新数据库
rs.next()----rs.previous()
rs.isFirst()----rs.isList()
rs.relative----rs.absolute()定位到行
rs.beforeFirst()----rs.afterList()某行前
>修改数据:
rs.absolute(2)移到指定行
rs.updateInt("id",222)
rs.updateRow()更新当前行
>插入:
rs.moveToInsertRow()
rs.updateString(1,"101")
rs.updateString(2,"name")
rs.insertRow()
>删除:
rs.absolute(5)
rs.deleteRow()
6、执行sql语句
Statement:静态sql语句
PreparedStatement:执行动态sql
CallableStatement:执行存储过程
7、关闭连接顺序与建立顺序相反
resultSet.close()->statement.close()->connection.close()
案例:
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("加载驱动异常");
e.printStackTrace();
}
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","123456");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from info where id=1");
while(rs.next()){
out.println(rs.getString(1)+" "+rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
5、动态sql语句执行接口PreparedStatement(继承于Statement)
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","123456");
String sql="insert into info (id,name) value(?,?)";
PreparedStatement stmt=conn.prepareStatement(sql);
stmt.setString(1,"4");
stmt.setString(2,"fei");
stmt.execute();
stmt.close();
conn.close();
![这里写图片描述](//img-blog.csdn.net/20180320133920975?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L2xpbmtpbmdmZWk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)