Java笔记(二)--Eclipse 连接SQlServer

                            连接代码如下:
 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差不多。
 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了。  
以上是 Java笔记(二)--Eclipse 连接SQlServer 的全部内容, 来源链接: utcz.com/z/391872.html








