java 连接MySQL 并测试是否成功。

 

  1. package com.test.tool;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8. import java.sql.Statement;  
  9.   
  10.   
  11. public class JDBCUtlTool {  
  12.     public static Connection getConnection(){  
  13.         String driver="com.mysql.jdbc.Driver";   //获取mysql数据库的驱动类  
  14.         String url="jdbc:mysql://localhost:3306/test"; //连接数据库(kucun是数据库名)  
  15.         String name="root";//连接mysql的用户名  
  16.         String pwd="123456";//连接mysql的密码  
  17.         try{  
  18.             Class.forName(driver);  
  19.             Connection conn=DriverManager.getConnection(url,name,pwd);//获取连接对象  
  20.             return conn;  
  21.         }catch(ClassNotFoundException e){  
  22.             e.printStackTrace();  
  23.             return null;  
  24.         }catch(SQLException e){  
  25.             e.printStackTrace();  
  26.             return null;  
  27.         }  
  28.     }  
  29.       
  30.     public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){  
  31.         try{  
  32.             if(rs!=null){  
  33.                 rs.close();  
  34.             }  
  35.         }catch(SQLException e){  
  36.             e.printStackTrace();  
  37.         }  
  38.         try{  
  39.             if(ps!=null){  
  40.                 ps.close();  
  41.             }  
  42.         }catch(SQLException e){  
  43.             e.printStackTrace();  
  44.         }  
  45.         try{  
  46.             if(conn!=null){  
  47.                 conn.close();  
  48.             }  
  49.         }catch(SQLException e){  
  50.             e.printStackTrace();      
  51.         }  
  52.     }  
  53.       
  54.     public static void main(String[] args) throws SQLException  
  55.     {  
  56.           
  57.         Connection cc=JDBCUtlTool.getConnection();  
  58.           
  59.         if(!cc.isClosed())  
  60.   
  61.         System.out.println("Succeeded connecting to the Database!");  
  62.         Statement statement = cc.createStatement();  
  63.         String sql = "select * from test2";  
  64.         ResultSet rs = statement.executeQuery(sql);  
  65.         while(rs.next()) {  
  66.             System.out.println(rs.getString("id")+"");  
  67.         }  
  68.   
  69.   
  70.     }  
  71. }  

Logo

更多推荐