代碼都已經打完了,但是一直連接不成功,sqlserver數據庫驅動也下下來了並放到buding path裡了,sqlserver協議tcp/ip也更改了,數據庫也用用戶名密碼登陸了,還差什麼啊,求大神指教,下面是代碼,都是網上的,應該沒錯。
package com.demo;
import java.io.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
Servlet implementation class register
*/
@WebServlet("/register.do")
public class register extends HttpServlet {
public Connection cn;
public PreparedStatement ps;
public ResultSet rs;
//連接數據庫
public void getCn()
{
String url="jdbc:microsoft:sqlserver://192.168.1.119:1433;DatabaseName=Web";
String driverpath="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String name="sa";
String pwd="123456";
try{
Class.forName(driverpath);
cn=DriverManager.getConnection(url,name,pwd);
if(cn!=null)
{
System.out.println("ok");
cn.close();
}
else
System.out.println("數據庫連接失敗!");
}catch(Exception e)
{
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
//得到post資源
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out=response.getWriter();
String name=request.getParameter("username");
String pwd=request.getParameter("password");
System.out.println(name);
System.out.println(pwd);
if(this.insert(name,pwd)==true)
{
out.println("注冊成功");
}
else
out.println("注冊失敗");
out.flush();
out.close();
}
//注冊添加數據
public boolean insert(String name,String pwd)
{
getCn();
boolean b=false;
String sql="insert into login values(?,?)";
try{
ps=cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, pwd);
ps.execute();
b=true;
}catch(Exception e)
{
e.printStackTrace();
}finally {
try{
if(rs!=null)
rs.close();
else if(ps!=null)
ps.close();
else if(cn!=null)
cn.close();
}catch(Exception e){}
}
return b;
}
}
是顯示數據庫連接失敗還是拋異常了