eclipse 连接MySQL、SQL server数据库

连接SQL server

public class Test2 {

    public static void main(String[] args) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.out.println("加载数据库驱动成功");
            String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=ipt";//声明数据库test的url
            String user="user";//数据库账号
            String pass="password";//数据库密码
            //建立数据库连接,获得连接对象conn
            Connection conn=DriverManager.getConnection(url,user,pass);
            System.out.println("数据库连接成功");
            Statement stmt=conn.createStatement();//创建一个Statement对象
            String sql="select * from cdr_raws";//生成一条sql语句
            ResultSet rs=stmt.executeQuery(sql);//执行查询,把查询结果赋值给结果集对象
            String callingPartyNumber;//声明2个变量分别为用户名,密码
            while(rs.next()){//遍历结果集
                callingPartyNumber=rs.getString("callingPartyNumber");//
                System.out.println(callingPartyNumber);
            }
            System.out.println("获得查询结果集");
            conn.close();
            System.out.println("关闭数据库连接对象");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//加载数据库驱动
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

连接MySQL

public class Test2 {

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("加载数据库驱动成功");
            String url="jdbc:mysql://localhost:3306/test";//声明数据库test的url
            String user="root";//数据库账号
            String pass="pass";//数据库密码
            //建立数据库连接,获得连接对象conn
            Connection conn=DriverManager.getConnection(url,user,pass);
            System.out.println("数据库连接成功");
            Statement stmt=conn.createStatement();//创建一个Statement对象
            String sql="select * from account";//生成一条sql语句
            ResultSet rs=stmt.executeQuery(sql);//执行查询,把查询结果赋值给结果集对象
            String callingPartyNumber;//声明2个变量分别为用户名,密码
            while(rs.next()){//遍历结果集
                callingPartyNumber=rs.getString("name");//
                System.out.println(callingPartyNumber);
            }
            System.out.println("获得查询结果集");
            conn.close();
            System.out.println("关闭数据库连接对象");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//加载数据库驱动
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/RealWorld/p/8989226.html