Oracle:jdbc:oracle:thin:@<host><:port>:<database_name>
java,sql.Statement 和java.sql.PreparedStatement
语句对象,用于提交SQL语句;
Statement通常用于执行静态SQL语句,statement.excute(sql)即可提交;
PreparedStatement可以执行动态SQL语句,允许参数化查询,而且性能更好,还可以有效避免SQL注入式攻击,后面示例都使用PreparedStatement
java.sql.ResultSet:
指定SQL语句(通常为查询)执行返回的原始结果集,在实际开发我们通常对结果进行再封装,以方便调用
实体类Personpackage com.jdbc.entity;
//实体类Person,属性与数据库中字段对应
public class Person {
private Integer id;
private String name;
private String gender;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ",, gender=" + gender
+ ", age=" + age + "]";
}
}
package com.jdbc.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtil {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1/hb?characterEncoding=utf-8";
private static String username = "root";
private static String password = "hjh123";
//静态代码块中注册加载驱动类
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//封装获取连接方法
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//封装关闭对象方法
public static void close(ResultSet rs, Statement statement, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.jdbc.demo;