欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

命令行运行Java代码连接SQLServer、MySQL

程序员文章站 2024-03-08 18:48:28
...
  1. 向CLASSPATH添加jar包
    命令行运行Java代码连接SQLServer、MySQL
    命令行运行Java代码连接SQLServer、MySQL
    命令行运行Java代码连接SQLServer、MySQL
  2. Java代码
// ********************连接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();
	}
}

命令行运行Java代码连接SQLServer、MySQL
若是不使用IDE,且java代码中需要第三方jar包,需要手动在CLASSPATH中添加。这样JDK才能搜索到依赖的jar包

相关标签: SQL Server