zoukankan      html  css  js  c++  java
  • JDBC的一些代码

    import java.sql.*;
    
    public class jdbc {
    	
    	//JDBC 驱动名及数据库名  URL
    	static final String JDBC_DRIVE = "com.mysql.jdbc.Driver";
    	static final String DB_URL = "jdbc:mysql://localhost:3306/runoob";
    	
    	static final String USER = "root";
    	static final String PASS = "root";
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Connection conn = null;
    		Statement stmt = null;
    	    try{
    	    	//注册JDBC驱动
    	    	Class.forName("com.mysql.jdbc.Driver");
    	    	
    	    	//打开链接
    	    	System.out.println("链接数据库...");
    	    	conn = DriverManager.getConnection(DB_URL, USER, PASS);
    	    	
    	    	//执行查询
    	    	System.out.println("实例化statement对象...");
    	    	stmt = conn.createStatement();
    	    	String sql;
    	    	sql = "select id, name, url from websites";
    	    	ResultSet rs = stmt.executeQuery(sql);
    	    	
    	    	//展开数据集
    	    	while(rs.next()){
    	    		int id = rs.getInt("id");
    	    		String name = rs.getString("name");
    	    		String url = rs.getString("url");
    	    		
    	    		//output data
    	    		System.out.print("id" +  id);
    	    		System.out.print(", name" +  name);
    	    		System.out.print(", url" +  url);
    	    		System.out.print("
    ");
    	    	}
    	    	rs.close();
    	    	stmt.close();
    	    	conn.close();
    	    } catch(SQLException se) {
    	    	//处理JDBC错误
    	    	se.printStackTrace();
    	    } catch(Exception e) {
    	    	//处理Class.forName 错误
    	    	e.printStackTrace();
    	    } finally {
    	    	//关闭资源
    	    	try{
    	    		if( stmt != null )
    	    			stmt.close();
    	    	} catch(SQLException se2) {
    	    		//
    	    	}
    	    	/******************************/
    	    	try{
    	    		if( conn != null )
    	    			conn.close();
    	    	} catch(SQLException se3) {
    	    		se3.printStackTrace();
    	    	}
    	    }
    		System.out.println("完成");
    	}
    }
    

      JDBC的一些代码,自己在eclipse跑了一下,代码源自菜鸟教程!

  • 相关阅读:
    杭电2095--find your present (2) (异或)
    南阳168--房间安排(区间覆盖)
    南阳954--N!(数学)
    南阳--69(数的长度)
    杭电--N!(大数)
    杭电1005--Number Sequence
    杭电1108--最小公倍数
    动态规划:最长上升子序列(二分算法 nlogn)
    动态规划:最长上升子序列之基础(经典算法 n^2)
    vector函数用法
  • 原文地址:https://www.cnblogs.com/yspworld/p/9039583.html
Copyright © 2011-2022 走看看