使用jtds连接sqlserver数据库并获取所有数据库名称

package testMain;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestMain {

catch(java.lang.ClassNotFoundException e){
    System.out.println("hello world");

    Connection conn = getConnection();
    try {
        Statement st=conn.createStatement();
        //st.execute("insert into dept(name) values(\‘5555\‘)");
        ResultSet rset=st.executeQuery("SELECT Name from Master..SysDatabases ORDER BY Name" );
        int rowCount = 0;   
        while(rset.next()) {   
           System.out.println(rset.getString("name"));
          rowCount++;   
        }  
       System.out.println(rowCount);
        st.close();
        conn.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static Connection getConnection(){
    String dbDriver = "net.sourceforge.jtds.jdbc.Driver";
    String strConnection = "jdbc:jtds:sqlserver://localhost:1433/";
    String user = "sa";
    String password = "123";
    Connection conn = null;
    try{
    //定义连接驱动
    Class.forName(dbDriver);
    }
    catch(java.lang.ClassNotFoundException e){
    System.err.println("DBconnection():"+e.getMessage());
    }
    //--------连接SQL数据库------------------
    try
    {
    conn = DriverManager.getConnection(strConnection,user,password);
    }
    catch(SQLException ex)
    {
    System.err.println("aq.executeQuery:"+ex.getMessage());
    }
    return conn;
    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。