package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestQuery {
public static void main(String[] args) {
// 1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 2.创建连接
Connection conn = null;
Statement stmt = null;
ResultSet r = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_2", "root", "root");
// 3.获取Statement对象
stmt = conn.createStatement();
// 4.通过stmt对象实现对数据库的查询
String sql = "select * from dept";
// 5.通过查询范围结果集(游标)
r = stmt.executeQuery(sql);
// 6.通过循环获取游标中所有的值
while(r.next()){
System.out.println(r.getInt(1) + " "
+ r.getString(2) + " "
+ r.getString(3) + " "
+ r.getDate(4));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (r != null){
r.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestQuery {
public static void main(String[] args) {
// 1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 2.创建连接
Connection conn = null;
Statement stmt = null;
ResultSet r = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_2", "root", "root");
// 3.获取Statement对象
stmt = conn.createStatement();
// 4.通过stmt对象实现对数据库的查询
String sql = "select * from dept";
// 5.通过查询范围结果集(游标)
r = stmt.executeQuery(sql);
// 6.通过循环获取游标中所有的值
while(r.next()){
System.out.println(r.getInt(1) + " "
+ r.getString(2) + " "
+ r.getString(3) + " "
+ r.getDate(4));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (r != null){
r.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}