• Java JDBC典型运用


    package nh.spring.tools.db;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class TestDBConnection {
    	/**
    	 * 典型jdbc连接
    	 * 1,与数据库建立连接
    	   2,发送SQL语句
           3,处理返回结果
    	 */
    	static Connection con = null;
    	static Statement stmt = null;
    	static ResultSet rs = null;
    	
    	public static void main(String[] args) {	
    		try {
    			// 1、加载MYSQL驱动,这里MySQL的JDBC驱动类是com.mysql.jdbc.Driver,要求类路径中包含相应的Driver类
    			Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    			
    			// 2、连接到MYSQL,通过DriverManger来创建Connection对象,获取数据库连接
    			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vShop", "root", "niuheng"); 
    			
    			// 3、创建Statement用以执行SQL语句,或者可以使用PreparedStatement
    			Statement stmt = con.createStatement();
    			
    			// 4、执行SQL,获取结果
    			ResultSet rs = stmt.executeQuery("select * from user");
    			// 或者执行增删改操作,如:stmt.executeUpdate("delete * from blog");
    			
    			// 5、遍历并解析结果
    			while (rs.next()) {
    				long id = rs.getLong("id"); // 获取id列
    				String username = rs.getString("username"); // 获取username列
    				System.out.println("id:"+id+" Name:" +username);
    			}
    		} catch (Exception e) {
    			
    			// 如果有异常,进行异常处理
    			System.out.print("MYSQL ERROR:" + e.getMessage());
    			
    		} finally {
    			// 6、清理数据库连接相关的所有资源
    			try {
    				if (rs != null) {
    					rs.close();
    				}
    				
    				if (stmt != null) {
    					stmt.close();
    				}
    				
    				if (con != null) {
    					con.close();
    				}
    			} catch (SQLException ignored) {
    				
    			}
    		}
    	}
    
    }
    

      

  • 相关阅读:
    第一次项目总结
    8.16 CSS知识点7
    2016y9m22d 博文分享
    2016y9m8d
    2016y9m7d
    2016y9m6d
    2016y9m5d
    2016.9.2博文分享!
    2016y8m16d
    2016y8m15d
  • 原文地址:https://www.cnblogs.com/hylinux/p/6144276.html
Copyright © 2020-2023  润新知