JDBC数据库连接实例分享

来源:互联网 发布:删除旧的windows文件夹 编辑:程序博客网 时间:2024/06/08 11:13

    JDBC数据库连接

import java.sql.*;public class JDBCTest{static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";     //相当于引入Mysql.Data   static final String DB_URL = "jdbc:mysql://localhost/jp1";         //相当于引入ip地址   //  Database credentials   static final String USER = "root";                 //用户名和密码   static final String PASS = "1";      public static void main(String[] args) {   Connection conn = null;   Statement stmt = null;   try{      //STEP 2: Register JDBC driver      Class.forName("com.mysql.jdbc.Driver");          //加载jar包      //STEP 3: Open a connection      System.out.println("Connecting to database...");      conn = DriverManager.getConnection(DB_URL,USER,PASS);      //STEP 4: Execute a query      System.out.println("Creating statement...");      stmt = conn.createStatement();      String sql;      sql = "SELECT Userid,SID,Name,surname FROM jp_personnel";      ResultSet rs = stmt.executeQuery(sql);      //STEP 5: Extract data from result set      while(rs.next()){         //Retrieve by column name          String userid = rs.getString("Userid");         String name = rs.getString("Name");         String surname = rs.getString("surname");                  //Display values         System.out.print("ID: " + userid);         System.out.print(", 姓名: " + name);         System.out.print(", 姓氏: " + surname+"\n");      }      //STEP 6: Clean-up environment      rs.close();      stmt.close();      conn.close();   }catch(SQLException se){      //Handle errors for JDBC      se.printStackTrace();   }catch(Exception e){      //Handle errors for Class.forName      e.printStackTrace();   }finally{      //finally block used to close resources      try{         if(stmt!=null)            stmt.close();      }catch(SQLException se2){      }// nothing we can do      try{         if(conn!=null)            conn.close();      }catch(SQLException se){         se.printStackTrace();      }//end finally try   }//end try   System.out.println("Goodbye!");}//end main}//end FirstExample - by www.yiibai.com

此时要引入mysql的jar包,要把我们的jar包和类放在同一目录下


0 0
原创粉丝点击