示例代码
将以下示例复制并粘贴到 JDBCExample.java 中,编译并运行如下 -
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
System.out.println("Connecting to a selected database...");
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {
System.out.println("Connected database successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
现在让我们编译上面的例子如下 -
C:\>javac JDBCExample.java
C:\>
当你跑 JDBCExample,它产生以下结果 -
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
C:\>