现在是手工入门,就不太依赖IDE,使用MYSQL的JDBC的JAR包连数据库的方式如下:
演示文件内容:
package cc.openhome; import java.sql.*; public class ConnectionDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); String jdbcUrl = "jdbc:mysql://1.2.3.4:3306/DemoDB"; String user = "demo"; String passwd = "demo_pass"; Connection conn = DriverManager.getConnection(jdbcUrl, user, passwd); System.out.printf("Database has %s%n", conn.isClosed()? "closed": "opened"); } }
编译及运行命令:
D:\learn>javac -cp . -d . ConnectionDemo.java D:\learn>java -cp .;mysql-connector-java-5.1.38-bin.jar cc.openhome.ConnectionDemo
注意:
-cp .;mysql-connector-java-5.1.38-bin.jar 是指定classpath即包括当前目录,也包括当前目录下的mysql-connector-java-5.1.38-bin.jar,以分号分隔。如果将mysql-connector-java-5.1.38-bin.jar解压在当前目录,D:\learn>java -cp . cc.openhome.ConnectionDemo也OK的。
时间: 2024-11-06 20:06:35