public static void main(String[] args) throws Exception {
Connection conn = JDBCUtils.getCon();
//定义查询的语句
String sql = "select * from accounting";
PreparedStatement psmt = (PreparedStatement) conn.prepareCall(sql);
// 执行查询语句
ResultSet rs = psmt.executeQuery();
// 打印查询结果
System.out.println("id\tname\tage");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String age= rs.getString("age");
System.out.println(id+"\t"+name+"\t"+age);
}
// 关闭数据库
rs.close();
psmt.close();
conn.close();
}
class JDBCUtils {
private static final String URL = "jdbc:mysql://localhost:3306/day12";
private static final String USER = "root";
private static final String PASSWORD = "root";
/*
* static是静态代码块,把注册驱动的代码放在这里,在使用这个类的时候会先运行代码块儿
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("数据库注册失败");
}
}
/*
* 提供一个连接数据库的方法,返回值是Connection类型
*/
public static Connection getCon() {
Connection con = null;
try {
// 连接数据库
con = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
System.out.println("数据库连接失败");
}
return con;
}
}
20161124224617314 .jpg (15.99 KB, 下载次数: 32)
新建lib文件
20161124225349676.jpg (59.96 KB, 下载次数: 36)
导入jar包
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |