JDBC连接SQL Server数据库

时间:2022-11-17 06:55:37

测试环境

数据库:SQL Server 2008 R2,创建数据库名:TestDemo,表:User,字段如下:

  字段 字段
id UName UPass

sqljdbc.jar下载地址:
依赖的Jar包:sqljdbc.jar

http://download.csdn.net/download/wu996489865/9375672

step1  将下载后的jar包放在WebRoot/WEB-INF/lib文件夹

step2  创建两个简单的页面进行测试,分别为index.jsp(注册页)和insert.jsp(处理页)
index.jsp(注册页)代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<form action="insert.jsp" method="post">
用户名:<input type="text" name="name"/><br>
密码:<input type="password" name="pass" /><br>
<input type="submit" name="submit" value="注册"/>
</form>
</body>
</html>

step3  insert.jsp(处理页)代码:

<%@ page language="java" import="java.sql.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <%
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=TestDemo","sa","luotian");
Statement state=conn.createStatement();
int result=state.executeUpdate("insert into [User](UName,UPass) values('"+request.getParameter("name")+"','"+request.getParameter("pass")+"')");
if(result==1)
out.println("用户注册成功");
else
out.println("用户注册失败");
}
catch(SQLException e)
{
out.println(e);
}
%>
</body>
</html>