串連代碼如下:Code
public class Test_SQLServer {
static Connection conn =null;
static Statement stmt=null;
static ResultSet rs=null;
private static boolean Conn_SQLServer(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver")
.newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;
DatabaseName=test";
String user="sa";
String password="sa";
conn= DriverManager.getConnection(url,user,password);
try{
stmt=conn.createStatement();
System.out.println("串連成功!");
return true;
}
catch(SQLException s_e){
System.out.println("s_E"+s_e.getMessage().toString());
return false;
}
}
catch(SQLException s_e){
System.out.println("串連錯誤!SQLException "+s_e.toString());
return false;
}
}
private static void ExeSQL(String sql,int flag){
try{
long begin_SQL_Ticks=System.currentTimeMillis();
boolean sql_exe=false;
sql_exe=stmt.execute(sql);
long end_SQL_Ticks=System.currentTimeMillis();
if(sql_exe){
//如果要求返回結果
if(flag==1){
rs=stmt.getResultSet();
rs.first();
while(!rs.isLast()){
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getInt(2)+" ");
System.out.print(rs.getInt(3)+"\n");
rs.next();
}
rs.last();
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getInt(2)+" ");
System.out.print(rs.getInt(3)+"\n");
long show_Ticks=System.currentTimeMillis();
System.out.println("顯示共耗時:"+(show_Ticks-end_SQL_Ticks)+"毫秒");
}
}
System.out.println("執行SQL語句共耗時:"+(end_SQL_Ticks-begin_SQL_Ticks)+"毫秒");
}
catch(SQLException s_e){
System.out.println(s_e.getMessage());
}
裝驅動,打sp4補丁,再串連,一切都和MySQL差不多。Code
public static void main(String[] args) {
if(Conn_SQLServer()){
ExeSQL("use test;",2);
ExeSQL("create table test_1(name varchar(12),age smallint,id int)",2);
ExeSQL("insert into test_1 values('zs',21,53535)",1);
ExeSQL("select * from test_1",1);
//ExeSQL("drop table test_1",2);
}
建表,插入資料,一切ok.但查詢時卻除了問題,報錯:
[Microsoft][SQLServer 2000 Driver for JDBC]Unsupported method: ResultSet.first
貌似時JDBC不支援某個方法—這樣的話,麻煩大了。
好在經過搜尋了,發現其實可以解決
綜合分析: createStatement()含有的參數說明如下:
1.TYPE_FORWORD_ONLY,只可向前滾動;
2.TYPE_SCROLL_INSENSITIVE,雙向滾動,但不及時更新,就是如果資料庫裡的資料修改過,並不在ResultSet中反應出來。
3.TYPE_SCROLL_SENSITIVE,雙向滾動,並及時追蹤資料庫的更新,以便更改ResultSet中的資料。
因此在改成createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE)即可解決問題。
因此將stmt=conn.createStatement();寫成
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);就ok了。