今天看到JDBC的部分,其实以前就看过了,只是记性比较差,所以才写下来,以备以后查看。
1. 首先,导入对应数据库的jar包(我这里使用的是 MySQL)
2. 编写代码
package com.zjh.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 测试JDBC在Java中的运用
*
* @author ZJH_PC
*
*/
public class JDBCConnect {
public static void main(String[] args) {
// 运用JDK7的try-with-resource新特性
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/test", "root", "1");
Statement statement = connection.createStatement()) {
// 加载MySQL驱动
Class.forName("com.mysql.jdbc.Driver");
// String sql = "insert into student values('zjh',12)";
String sql = "select * from student";
// execute的返回值有点出乎意料,附上jdk文档里的介绍
// Returns:true if the first result is a ResultSet object,
// false if it is an update count or there are no results
boolean result = statement.execute(sql);
if (result) {
// System.out.println("success");
//若有结果,则遍历出结果
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("name")
+ "'s age is " + resultSet.getInt("age"));
}
} else {
System.out.println("No Result");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}