java连接mysql数据库

来源:互联网 发布:方正小标宋简体 mac 编辑:程序博客网 时间:2024/05/17 23:26
  1. /** 
  2.  * 单独的java程序连接mysql数据库 
  3.  * author:JavaAlpha 
  4.  * date :2011-3-31 20:48:28 
  5.  * IDE:EmEditor Version 9.16 
  6.  */  
  7. import java.sql.*;  
  8. public class Test {  
  9. public static void main(String[] args){  
  10. String driver = "com.mysql.jdbc.Driver";  
  11. String url = "jdbc:mysql://127.0.0.1:3306/test";  
  12. String user = "root";  
  13. String password = "123456";  
  14. try {  
  15. Class.forName(driver);   
  16.         Connection conn = DriverManager.getConnection(url, user, password);  
  17.         if(!conn.isClosed())  
  18.             System.out.println("Succeeded connecting to the Database!");   
  19.             Statement statement = conn.createStatement();  
  20.             String sql = "select * from t_user order by id desc";  
  21.               
  22.       ResultSet rs = statement.executeQuery(sql);         
  23.       String name = null;  
  24.       while(rs.next())   
  25.             {  
  26.              name = rs.getString("sourse");  
  27.              System.out.println(rs.getString("id")+"/t"+rs.getString("href") + "/t" + name + "/t" + rs.getString("title")+"/t"+rs.getString("time"));  
  28.             }  
  29.             rs.close();  
  30.             conn.close();  
  31.            } catch(ClassNotFoundException e) {  
  32.             System.out.println("Sorry,can`t find the Driver!");  
  33.             e.printStackTrace();  
  34.            } catch(SQLException e) {  
  35.             e.printStackTrace();  
  36.            } catch(Exception e) {  
  37.             e.printStackTrace();  
  38.            }            
  39. }  
  40. }  
0 0
原创粉丝点击