.NET程序员学Java笔记[3]-TestSQLServer2005

/**
 * 说明:需要先配置MS SQL Server JDBC:
 * Window→Preferences→Java→Installed JRE
 * 如果果JRE6:Edit→add External JARs...→选择sqljdbc4.jar 
 * 如果是JRE5:Edit→add External JARs...→选择sqljdbc.jar
 */

package net.io99;

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

public class TestSQLServer2005 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 加载JDBC驱动
		String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=dnt25"; // 连接服务器和数据库sample
		String userName = "sa"; // 默认用户名
		String userPwd = "123456"; // 密码
		Connection dbConn;

		try {
			Class.forName(driverName);
			dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
			System.out.println("Connection Successful!"); // 如果连接成功控制台输出Connection Successful!

			Statement stmt = dbConn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from dbo.dnt_admingroups");

			// Now retrieve (all) the rows that matched the query
			while (rs.next()) {
				int name = rs.getInt(1);
				int fullName = rs.getInt(3);
				System.out.println("User " + name + " is named " + fullName);
			}
			rs.close(); // All done with that resultset
			stmt.close(); // All done with that statement
			dbConn.close();
			System.in.read();
		} catch (Exception e) {
			e.printStackTrace();
		}finally
		{
			
		}
	}

}
 

你可能感兴趣的:(java,sql,.net,SQL Server,jdbc)