java 的 数据库连接测试类 (SQL server)

时间:2022-09-24 11:58:25

package com.xrom.ssh.test;

import java.sql.*;
import java.text.SimpleDateFormat;

/**
 * 测试sql server 数据库是否能连接
 * Created by bill xu on 2019/1/31.
 */
public class TestConn {
    public static void main(String[] args) {

        String DataBaseName = "mydb";//数据库名称
        String user = "sa";  //数据库用户名
        String Psd = "sa";    //数据库密码
        String name = "localhost";//数据库ip地址
        String instancename = "SQLEXPRESS";//实例名称

        //实例连接方式
        //如果式默认实例则不需要加实例名,直接这样jdbc:sqlserver://localhost;databaseName=mydb;user=sa;password=sa
        //https://bbs.csdn.net/topics/392190826
        String url = "jdbc:sqlserver://"+name +"instanceName="+instancename+
                ";databaseName="+DataBaseName+
                ";user="+user+";password="+Psd;//sa身份连接

        //数据库端口连接方式
//        String url = "jdbc:sqlserver://"+ name +":1433;databaseName="+DataBaseName+
//                ";user="+user+";password="+Psd;//sa身份连接

        // Declare the JDBC objects.
        try {
            // Establish the connection.
            System.out.println("begin.");
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.out.println(url);
            Connection conn = DriverManager.getConnection(url);
            System.out.println("数据库连接成功!!!");
            System.out.println("end.");

            Statement stmt = null;
            ResultSet rs = null;

            // Create and execute an SQL statement that returns some data.
            String SQL = "SELECT  * FROM [Real]";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(SQL);


            // Iterate through the data in the result set and display it.
            while (rs.next()) {
//                System.out.println("时间+" + rs.getTime(1));
//                java.util.Date date;
//                System.out.println("日期 +" + (date = rs.getDate(1)));
//                SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                System.out.println("first:" + format0.format(date.getTime()));
//                String timeStr = rs.getString(1);
//                java.util.Date sene =  format0.parse(timeStr);
//                System.out.println("second:" + format0.format(sene.getTime()));

                System.out.println(rs.getString(1) + " " + rs.getString(2));
            }

            conn.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}