简单描述下spring访问数据库的方式
1.java原生的访问数据库的方式
public Connection getConnection() throws ClassNotFoundException,
SQLException {
// 加载MySQL的JDBC的驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/test";
String username = "root";
String password = "123456";
// 创建与MySQL数据库的连接类的实例
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Database connection established");
return conn;
}
public void query() throws Exception {
Connection conn = getConnection();
try {
// 用conn创建Statement对象类实例
Statement sql_statement = conn.createStatement();
// 执行查询,用ResultSet类的对象,返回查询的结果
String query = "select * from person";
ResultSet result = sql_statement.executeQuery(query);
// 处理结果
while (result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
String age = result.getString("age");
System.out.println("id: " + id + " name: " + name + " age: " + age);
}