Java EE连接SQL Servet 2008的时遇到的一些问题及解决方法
2012-03-27 01:11 java线程例子 阅读(369) 评论(0) 编辑 收藏 举报错误一、com.microsoft.sqlserver.jdbc.SQLServerException:The TCP/IP connection to the host localhost, port 1433 has failed. Error:Connection refused: connect. Please verify the connection properties and checkthat a SQL Server instance is running on the host and accepting TCP/IPconnections at the port, and that no firewall is blocking TCP connections tothe port.
解决方法:
1.打开SQL Server配置管理器,在左侧双击SQL Server网络配置
2.在SQL Server的协议中,这时会看到右侧TCP/IP的状态被禁用了!右击开启。
3.最后,重新启动一下SQL Server服务。
详看下图:
1、
2、
错误二、java.sql.SQLException: Nosuitable driver found for jdbc:sqlserver://127.0.0.1:1433;databaseName=User atjava.sql.DriverManager.getConnection(Unknown Source)
1、确认Class.forName(driverName).newInstance();中driverName值为:com.microsoft.sqlserver.jdbc.SQLServerDriver
2、确认WEB-INF\lib文件夹下有sqljdbc4.jar
错误三、java.sql.SQLException:[Microsoft][ODBC驱动程序管理器]未发现数据源名称并且未指定默认驱动程序 at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source) at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(UnknownSource) at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source) atsun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) atjava.sql.DriverManager.getConnection(Unknown Source)
确认Connection conn = DriverManager.getConnection(url,"账号","密码");中url的值为:jdbc:sqlserver://127.0.0.1:1433;databaseName=数据库的名字
补充:
Java EE如何连接SQL Server 2008:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DB_Conn{ //JDBC驱动程序名 private String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //数据库名称 private String dateBaseName = "所要连接的数据库名称"; //用户名 private String username = "sql server 身份验证的账号"; //密码 private String password = "sql server 身份验证的密码"; private String url="jdbc:sqlserver://127.0.0.1:1433;databaseName="+dateBaseName; private Connection conn; private Statement sm; //建立连接 public void connectDB() { try { try { Class.forName(driverName).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } conn = DriverManager.getConnection(url,username,password); sm = conn.createStatement(); } catch (SQLException e) { System.out.println("数据库连接失败!"); } } //释放连接 public void closeDB(){ try{ if(sm != null){ sm.close(); } }catch(SQLException e){ System.out.println("关闭Statement失败!"); } try{ if(conn != null){ conn.close(); } }catch(SQLException e){ System.out.println("关闭Connection失败!"); } } public Statement getStatement() { return sm; } public void setStatement(Statement sm) { this.sm = sm; } }