在java和jsp中使用jdbc连接sql2008,首先要下载sql2008的jdbc驱动。下载安装后,到安装目录Microsoft JDBC Driver 4.0 for SQL Server下找到两个.jar文件,其中sqljdbc.jar是适用于sql2005,如果是2008,则使用sqljdbc.jar。将该jar文件拷贝到安装jdk的目录下的jre-->lib-->ext的文件夹下。如果是jsp连接,则还需将其拷贝到tomcat的lib目录下。现在自己的sql2008下建立一个数据库,我自己的是test。
1.首先用java连接:代码如下:
package org.kevin.yo; import java.sql.*; public class connectSql { public static void main(String[] srg) { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动 String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=test"; //连接服务器和数据库test String userName = "sa"; //默认用户名 String userPwd = "kevin"; //密码 Connection dbConn; Statement state=null; ResultSet rs=null; String sql="select * from stu_info"; try { Class.forName(driverName); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection Successful!"); //如果连接成功 控制台输出Connection Successful! state=dbConn.createStatement(); rs=state.executeQuery(sql); while(rs.next()){ String id= rs.getString(1); String name= rs.getString(2); String age = rs.getString(3); String sex=rs.getNString(4); System.out.println(id+""+name+""+age+""+sex+""); System.out.println("\n"); } } catch (Exception e) { e.printStackTrace(); } } }
输出结果:
2.jsp连接sql2008:代码如下:
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="ISO-8859-1"%> 3 <%@page import="java.sql.*" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 <%try{ 12 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 13 Connection conn= DriverManager.getConnection("jdbc:sqlserver://localhost;DatabaseName=test;user=sa;password=kevin"); 14 String sql = "select * from stu_info"; 15 Statement stmt=conn.createStatement(); 16 ResultSet rs = stmt.executeQuery(sql); 17 while(rs.next()){%> 18 <%=rs.getString(1) %><br/> 19 <%=rs.getString(2) %><br/> 20 <%=rs.getString(3) %><br/> 21 <%=rs.getString(4) %><br/> 22 <%} 23 out.println("successful!"); 24 }catch(Exception e){ 25 26 }%> 27 </body> 28 </html>
执行结果:
ok~~~我也是新手一枚,一家之言,欢迎大家一起交流学习。