原生jdbc操作数据库流程
第一步:Class.forName()加载数据库连接驱动;
第二步:DriverManager.getConnection()获取数据连接对象;
第三步:根据SQL获取sql会话对象,有2种方式 Statement、PreparedStatement ;
第四步:执行SQL处理结果集,执行SQL前如果有参数值就设置参数值setXXX();
第五步:关闭结果集、关闭会话、关闭连接。
class SqlConnectionUtil {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql;
String url = "jdbc:MySQL://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=UTF8";
try {
Class.forName("com.MySQL.jdbc.Driver");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
sql = "select * from user";
rs = stmt.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
System.out.println("姓名是:" + name);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}