MyEclipse连接MySQL

来源:互联网 发布:阿里云的dns怎么设置 编辑:程序博客网 时间:2024/05/17 07:52

 

  1. JDBCHelloWorld.java  
  2. import java.sql.SQLException;  
  3. /**  
  4. * 第一个 JDBC 的 HelloWorld 程序, 数据库访问 MySQL.  
  5. */  
  6. public class JDBCHelloWorld {  
  7.     /**  
  8.      * @param args  
  9.      * @throws SQLException   
  10.      */  
  11.     public static void main(String[] args) throws SQLException {  
  12.         // 1. 注册驱动  
  13.         try {  
  14.             Class.forName("com.MySQL.jdbc.Driver");  
  15.         } catch (ClassNotFoundException e) {  
  16.             // TODO Auto-generated catch block  
  17.             e.printStackTrace();  
  18.         }// MySQL 的驱动  
  19.         // 2. 获取数据库的连接  
  20.         java.sql.Connection conn = java.sql.DriverManager.getConnection(  
  21.                 "jdbc:MySQL://localhost/test?useUnicode=true&characterEncoding=GBK", "root", null);  
  22.         // 3. 获取表达式  
  23.         java.sql.Statement stmt = conn.createStatement();  
  24.         // 4. 执行 SQL  
  25.         java.sql.ResultSet rs = stmt.executeQuery("select * from user");  
  26.         // 5. 显示结果集里面的数据  
  27.         while(rs.next()) {  
  28.             System.out.println(rs.getInt(1));  
  29.             System.out.println(rs.getString("username"));  
  30.             System.out.println(rs.getString("password"));  
  31.             System.out.println();  
  32.         }      
  33.         // 6. 释放资源  
  34.         rs.close();  
  35.         stmt.close();  
  36.         conn.close();     
  37.     }  
原创粉丝点击