代码:
public class TestMysql {
public static voidmain(String[] args) {
// 1、加载JDBC驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.err.println("找不到驱动程序类 ,加载驱动失败!");
}
// 2、创建数据库的连接
String url ="jdbc:mysql://localhost:3306/cdbp?useUnicode=true&characterEncoding=gbk";
String username ="root";
String password ="";
Connection conn =null;
try {
conn =DriverManager.getConnection(url, username, password);
// 3、创建一个Statement
String sql = "select count(id)from t_patient";
PreparedStatement stmt =conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
// 4、处理数据
while (rs.next()) {
System.out.println(rs.getString(1));
}
// 5、关闭连接对象
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch(SQLException se) {
System.err.println("数据库操作败!");
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}