日期:2014-05-20 浏览次数:20862 次
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample"; //连接服务器和数据库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!
} catch (Exception e) {
e.printStackTrace();
}
public final class JdbcUtils
{
private static String url = "jdbc:sqlserver://localhost:1433; DatabaseName=UFSystem";
private static String user = "sa";
private static String password = "";
private JdbcUtils()
{
}
static
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (ClassNotFoundException e)
{
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs, Statement st, Connection conn)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
}