MyEclipse如何连接到SQLServer2005?


创建项目,添加sqljdbc.jar驱动包到项目中,百度下载sqljdbc.jar,项目右键-属性-构建路径-库-添加外部JAR


com.ck.sqlserver     Test.java:

package com.ck.sqlserver;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {
	Test(){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = JavaUtils.getConnection();
			String sql = "select * from dt_user";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getObject("name") + "\t" + rs.getObject("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JavaUtils.free(rs, ps, conn);
		}
	}
	public static void main(String[] args){
		new Test();
	}
}



com.ck.sqlserver  JavaUtils.java

package com.ck.sqlserver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JavaUtils {
	private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=db_test";
	private static String user ="sa";
	private static String password = "root";
	
	private JavaUtils(){
		
	}
		
	static{
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url,user,password);
	}
	
	public static void free(ResultSet rs, Statement st, Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				if(st!=null){
					try {
						st.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}finally{
						if(conn != null){
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}

}



配置sqlserver端口:

运行 ->cmd-> telnet 127.0.0.1 1433  如果打开失败,则需要配置sqlserver,配置完成重启服务器


MyEclipse如何连接到SQLServer2005?_第1张图片








你可能感兴趣的:(jdbc,MyEclipse,String,null,Class,sqlserver)