您的位置:首页 > 数据库

09..操作数据库

2016-06-17 11:08 295 查看
代码:
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
a6e2
(SQLException e) {
 
  e.printStackTrace();
 
 }
  }
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: