zoukankan      html  css  js  c++  java
  • MySQL之连接数据库的两种方法

    方法一:

    package DB;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class Conn {
    	// 定义一个变量
    	private static String message = "恭喜你,数据库链接成功!";
    
    	// 连接(加载)方法
    	public static Connection getConnection() {
    		try {
    			// 加载驱动
    			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    			// 实行连接参数 库名 用户名 和密码
    			return DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DataBaseName=ConstructionDB","sa","123456");
    		} catch (Exception e) {
    			// 打印异常
    			e.printStackTrace();
    			message = "数据库链接失败!";
    			return null;
    		}
    	}
    
    	// main方法
    	public static void main(String[] args) {
    		// 调用连接
    		getConnection();
    		// 测试情况
    		System.out.println(message);
    	}
    }

    方法二:

    package dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class BaseDao {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		getConn();
    	}
    	public static  Connection getConn() {
    		// TODO Auto-generated method stub
    		//加载驱动
    		Connection conn=null;
    		try {
    			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    			//连接数据库
    			conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DataBaseName=ConstructionDB","sa","123456");
    			System.out.println("连接成功");
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		return conn;
    		
    	}
    
    	public void closeConn(Connection conn,PreparedStatement pstmt,ResultSet rs) {
    		// TODO Auto-generated method stub
    		
    			try {
    				if(rs!=null)
    					rs.close();
    				if(pstmt!=null)
    					pstmt.close();
    				if(conn!=null)
    					conn.close();
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    	}
    
    }
    

      

  • 相关阅读:
    [puppet]如何设置全局exec path
    noVNC配置小结
    [CloudOps]解决Windows系列镜像在Openstack上蓝屏
    解决 /usr/bin/env: php: No such file or directory
    构建一个多区域的公有云平台:Stacklab
    ssh自动添加hostkey到know_hosts
    A few thoughts about Open Source Software
    简单翻译:Understanding Linux Network Internals 2.2. net_device Structure
    近期小结
    [Music]《our love will always last》
  • 原文地址:https://www.cnblogs.com/caidupingblogs/p/5945836.html
Copyright © 2011-2022 走看看