public class JDBCTest {
private static String URL = "jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8";
private static String USER = "root";
private static String PASSWORD = "root";
private static Connection connection = null;
private static Statement statement = null;
public static void main(String[] args) {
Statement statement = connectJDBC();
String sql = "select * from blog_user";
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("姓名:" + rs.getString("user_name") + "\\t"
+ "年龄:" + rs.getInt("user_age") + "\\t"
+ "最近登陆时间:" + rs.getTimestamp("user_login_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {//关闭掉连接释放资源
try {
if (rs != null) {
rs.close();
System.out.println("rs关闭成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
close();
}
}
//获取连接
public static Statement connectJDBC() {
try {
Class.forName("com.mysql.jdbc.Driver");//驱动加载
connection = DriverManager.getConnection(URL, USER, PASSWORD);//连接数据库
statement = connection.createStatement();//创建执行sql语句的对象
return statement;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void close() {
try {
if (connection != null) {
connection.close();
System.out.println("connection关闭成功");
}
if (statement != null) {
statement.close();
System.out.println("statement关闭成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Java使用JDBC连接数据库查询,之前刚刚接触代码没多久的时候写的
最新推荐文章于 2024-06-24 21:19:32 发布