Home  >  Article  >  Database  >  JDBC连接MySQL数据库实战演示

JDBC连接MySQL数据库实战演示

WBOY
WBOYOriginal
2016-06-07 14:52:34999browse

以下的文章主要介绍的是JDBC 连接MySQL数据库的实际操作过程以及在其实际操作中期实际应用代码的描述,以下就是JDBC 连接MySQL数据库的具体方案的描述,希望在你今后的学习中会有所帮助。 publicclassMySQLJdbc{ publicStringdriverName=com.MySQL.jdbc.Driv

  以下的文章主要介绍的是JDBC 连接MySQL数据库的实际操作过程以及在其实际操作中期实际应用代码的描述,以下就是JDBC 连接MySQL数据库的具体方案的描述,希望在你今后的学习中会有所帮助。

  public class MySQLJdbc {  
  public String driverName = "com.MySQL.jdbc.Driver";  
  public String url = "jdbc:MySQL://localhost:3306/oa";  
  public String userName = "root";  
  public String userPwd = "me";  
  /**  
  * Apr 19, 2009 12:49:55 PM  
  *   
  * @param args  
  */  
  public static void main(String[] args) {  
  MySQLJdbc my=newMySQLJdbc();  
  my.read();  
  }  
  public void read() {  
  String queryString = "select userName,realName from user";  
  Connection conn = null;  
  Statement st = null;  
  ResultSet rs = null;  
  try {  

  加载驱动

  Class.forName(driverName); 

  创建连接MySQL数据库

  conn = DriverManager.getConnection(url, userName, userPwd); 

  创建Statement

  st = conn.createStatement(); 

  执行sql语句,得到查询结果

  rs = st.executeQuery(queryString); 

  输出查询结果

  while (rs.next()) {  
  System.out.println("userName:" + rs.getString("userName")  
  + " realName:" + rs.getString("realName"));  
  } 

  关闭资源

  rs.close();  
  st.close();  
  conn.close();  
  } catch (Exception ex) {  

  输出错误信息

  ex.printStackTrace();  
  } finally { 

  finally子句总是会执行(就算发生错误),这样可以保证资源的绝对关闭

  try {  
  if (rs != null)  
  rs.close();  
  } catch (SQLException e) {  
  e.printStackTrace();  
  }  
  try {  
  if (st != null)  
  st.close();  
  } catch (SQLException e) {  
  e.printStackTrace();  
  }  
  try {  
  if (conn != null)  
  conn.close();  
  } catch (SQLException e) {  
  e.printStackTrace();  
  }  
  }  
  }  
  }  

  以上的相关内容就是对JDBC 连接MySQL数据库的介绍,望你能有所收获。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn