Command line to run Java code to connect SQLServer, MySQL

  1. Adding jar package to the CLASSPATH
    Here Insert Picture Description
    Here Insert Picture Description
    Here Insert Picture Description
  2. Java code
// ********************连接SQLServer**************************
import java.sql.*;

public class ConnectSQLServer {
	public static void main(String[] args) {
		Connection connection;
		String driver   = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String url      = "jdbc:sqlserver://localhost:1433;DatabaseName=Java8";
		String user     = "sa";
		String password = "fanyi";

		try {
			Class.forName(driver); 
			connection = DriverManager.getConnection(url, user, password);

			if (connection != null) {
				System.out.println("Success.");
			} else {
				System.out.println("Fail.");
			}

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

}

// ********************连接Mysql**************************

import java.sql.*;

public class ConnectMysql {
	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		String url      = "jdbc:mysql://localhost:3306/hibernate?useSSL=true";
		String user     = "root";
		String password = "fanyi";
		Connection connection = DriverManager.getConnection(url, user, password);

		if (connection != null) {
			System.out.println("Success.");
		} else {
			System.out.println("Fail.");
		}

		connection.close();
	}
}

Here Insert Picture Description
If not using the IDE, and the need for third-party jar java code packet, in the need to manually add the CLASSPATH. Such JDK to search for dependent jar package

Published 50 original articles · won praise 38 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_42250302/article/details/104055910