用JDBC连接,你首先要搞清楚是sql server 2000还是2005,如果是2000的话需要sp3及其以上版本。2000的链接代码如下:
import java.sql.*;
public class DbTest {
Connection con;
Statement sta;
ResultSet rs;
String driver;
String url;
String user;
String pwd;
public DbTest()
{
driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
url="jdbc:microsoft:sqlserver://localhost;DatabaseName=数据库名称";
user="sa";
pwd="";
init();
}
public void init()
{
try
{
Class.forName(driver);
System.out.println("Driver is OK!");
con=DriverManager.getConnection(url, user, pwd);
System.out.println("Connection is OK!");
sta=con.createStatement();
rs=sta.executeQuery("Select * from 表名");
while(rs.next())
{
System.out.println(rs.getString("字段名"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args [])
{
new DbTest();
}
}
2005的把driver和url分别改为:
String driver = “com.microsoft.sqlserver.jdbc.SQLServerDriver”;
String url = “jdbc:sqlserver://localhost:1433; DatabaseName=数据库名”;
依然采用jdbc的方式,只是jdbc的代码可以写到jsp的《%%》中。
代码如
public class JDBC {
private static Connection conn=null;
private static Statement stmt=null;
private static ResultSet rs=null;
public static void main(String[] args) throws SQLException {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/数据库名","sa","sa");
stmt=conn.createStatement();
String sql="select * from 表";
rs=stmt.executeQuery(sql);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn.close();
rs.close();
stmt.close();
}
}
}
我这个是jtds的驱动,你可以换一个,写法都类似的
建议看看书。。。。。