JSP连接到SQL server2008设置方法

一、配置好jdk环境和tomcat服务器

二、在控制面板中“管理工具”启动ODBC配置程序 ,添加sql server新数据源,其它默认设置,最后测试连接。

三、首先去微软官网下载数据库驱动程序包,解压其中的sqlserver到tomcat服务器下\Tomcat 6.0\webapps\ROOT\WEB-INF\classes文件夹下(classes文件夹我是新建的)。按如下代码编写就可以了(一下路径和用户密码要自行修改):

<%@ page contentType="text/html; charset=gb2312" %>
<%@ page info="database handler"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>



数据库连接实验



<%
  String sDBDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  //与解压到tomcat服务器那个文                                                                          //件路径相同
    String sConnStr = "jdbc:sqlserver://localhost:1433;DatabaseName=try";//“try”的意思就是与数据                        //库设置的数据源名对应;与数据库中的名称要一致,必须要在sql中建立相应数据库
Connection Con = null;
Statement Stmt = null;
try
{
try
{
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException e)
{
out.print("Connect to Database error: " + e.getMessage());
}
try
{
  Con = DriverManager.getConnection(sConnStr,"linxia","123");//设置你登陆sql的用户和密                                                                          //码;例如:用户:“linxia”
  }                                                            //密码:“123”(这是sql验证方式)
catch(SQLException e)
{
out.print(e.toString());
}

Stmt = Con.createStatement();
String query="CREATE TABLE GUEST" +
"(NUM VARCHAR(32),"+
"USERNAME TEXT,"+
"CONTENT TEXT,"+
"PASSWORD INTEGER,"+
"TOTAL INTEGER,"+
"REALNAME TEXT)";
Stmt.executeUpdate(query);
}
catch (Exception e) {}
out.println("恭喜,数据库连接创建成功!");
%>


//经过小弟测试成功

//

SQL数据库驱动程序包:http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=a737000d-68d0-4531-b65d-da0f2a735707

JDK1.6官方下载_JDK6官方下载地址:http://www.java.net/download/jdk6/6u10/promoted/b32/binaries/jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008.exe

//tomcat下载地址:http://tomcat.apache.org/download-60.cgi(下载32-bit/64-bit Windows Service Installer (pgp, md5)版本)

另附其它教程:http://www.bccn.net/Article/web/jsp/jszl/200804/7168.html


你可能感兴趣的:(JSP)