JDBC 是Java数据库连接技术的简称,提供连接各种常用数据库的能力
DriverManager类
Connection 接口
Statement 接口
ResultSet 接口
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
… …
}
Connection conn = DriverManager.getConnection(url,user,pass);
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/epet";
String user = "epetadmin";
String password = "0000";
try {
conn = DriverManager.getConnection(url,user,password);
//省略代码 … …
} catch (SQLException e) {
… …
}
Statement stmt = conn.createStatement();
返回值类型 | 方法名 | 方法说明 |
---|---|---|
ResultSet | executeQuery( String sql ) | 执行SQL查询,返回结果集 |
int | executeUpdate( String sql ) | 执行SQL增删改,返回受影响行数 |
boolean | execute( String sql) | 执行任意SQL,返回布尔值,表示是否有结果集返回 |
//示例代码 主人登录
Statement st = null;
//获取用于向数据库发送sql语句的statement
st = conn.createStatement();
//向数据库发sql
String sql = "select * from master where name= '"+name+"' and password = '"+password+"' " ;
st.executeQuery(sql);
继承Statement接口,预编译,避免SQL注入的隐患
什么是SQL注入:
String sql = "select * from master where name= '"+name+"' and password = '"+password+"' " ;
//name = "张三" password = 12'or'1'='1
String sql = "select * from master where name= '张三' and password = '12'or'1'='1' " ; //永真式
PreparedStatement st = conn.preparedStatement();
//示例代码 更新狗狗信息到数据库
Connection conn = null;
PreparedStatement pstmt = null;
//建立连接
… …
//使用占位符的SQL语句
String sql="update dog set health=?,love=? where id=?";
//创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
//设置每个输入参数的值
pstmt.setInt(1, 80);
pstmt.setInt(2, 15);
pstmt.setInt(3, 1);
//执行SQL
pstmt.executeUpdate();
//关闭连接
… …
next():移动到下一行
Previous():移动到前一行
//判断是否有结果集
if(rs.next()){
...
}
//遍历结果集获取数据
while(rs.next()){
...
}
getObject(string columnName)
System.out.println("id=" + rs.getObject(1));
System.out.println("name=" + rs.getObject("name"));
getString(String columnName)
int id = rs.getInt(1);
String name = rs.getString("name");
if(rs!=null){
try{
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try{
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}