Myeclipse中创建Web Project与SQL Server 2014连接方案

BaseDao.java文件 

package dao.impl;

import java.sql.*;

public class BaseDao {
	public final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	public final static String url = "jdbc:sqlserver://localhost:1433;DataBaseName =lx";
	
	public final static String dbName = "sa";	//数据库用户名
	public final static String dbPass = "sa123456";		//数据库密码
	
	public Connection getConn() throws ClassNotFoundException,SQLException{
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url,dbName,dbPass);
		return conn;
	}
	
	public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
		if(rs!= null){
			try{
				rs.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		if(pstmt!= null){
			try{
				pstmt.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		if(conn!= null){
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
		
		public int executeSQL(String preparedSql,String[] param){
			Connection conn = null;
			PreparedStatement pstmt = null;
			int num = 0;
			
			try{
				conn = getConn();
				pstmt = conn.prepareStatement(preparedSql);
				if(param!= null){
					for(int i=0;i<param.length;i++){
						pstmt.setString(i+1,param[i]);
					}
				}
				num = pstmt.executeUpdate();
			}catch(ClassNotFoundException e){
				e.printStackTrace();
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				closeAll(conn,pstmt,null);
			}
			return num;
		}
		
}
		

BaseDaoTest.java文件 

package test;

import java.sql.Connection;
import java.sql.SQLException;

import dao.impl.BaseDao;

public class BaseDaoTest {
	public static void main(String[] args) {
		BaseDao baseDao = new BaseDao();
		Connection conn = null;
		try{
			System.out.println("准备连接");
			conn = baseDao.getConn();
			System.out.println("连接成功");
		}catch(ClassNotFoundException e){
			System.out.println("连接失败1");
			e.printStackTrace();
		}catch(SQLException e){
			System.out.println("连接失败2");
			e.printStackTrace();
		}finally{
			System.out.println("真的连接成功了");
			baseDao.closeAll(conn, null, null);
		}
	}
}

文件结构如下:

然后,导入驱动jar包,先将jar包随便创个文件放进去。

比如我放在了这里面

然后对着这个sqljdbc41.jar,右键点击选择【Build path】,然后选择【Add to Build path】

x

这个时候可以看到

导入完成,在上方会出现Referenced libraries目录,查看其下是否有引入的SQL Server的jar包,如果有表明引入成功。

运行驱动类连接程序

结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值