问题描述
- Java web jdbc怎么连接数据库,要配置什么啊
-
代码都已经打完了,但是一直连接不成功,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;
}
- @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
}
- Servlet implementation class register
解决方案
是显示数据库连接失败还是抛异常了
解决方案二:
Java Web数据库配置
解决方案三:
try{
Class.forName(driverpath);
cn=DriverManager.getConnection(url,name,pwd);
if(cn!=null)
{
System.out.println("ok");
cn.close();
}
你拿到cn然后直接给它关闭了。。怎么调用cn.preparestatement()方法。。