import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class L43 { public static final String url = "jdbc:mysql://localhost:3306;DatabaseName=yggl"; private final static String username = "root"; private final static String password = "ziyexue"; public static void main(String args[]) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("加载驱动成功!"); } catch (Exception e) { e.p rintStackTrace(); System.out.println("OK"); } try { String url="jdbc:mysql://localhost:3306/yggl"+"?useUnicode=true&characterEncoding=UTF-8&userSSL=true&serverTimezone=UTC"; Connection dbConn=DriverManager.getConnection(url, username, password); Statement st= dbConn.createStatement(); System.out.println("连接数据库成功!"); } catch (Exception e) { e.printStackTrace(); System.out.println("SQL Server连接失败!"); } } } 这段代码哪有问题
时间: 2024-02-14 08:07:56 浏览: 181
这段代码有两个问题:
1. 在`url` 变量中,`DatabaseName` 应该改为 `databaseName`,并且连接字符串最后应该加上具体的数据库名,正确的格式应该是 `jdbc:mysql://localhost:3306/yggl`。
2. `e.p rintStackTrace()` 中间的空格应该去掉,正确的写法是 `e.printStackTrace()`。
下面是修改后的代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class L43 {
public static final String url = "jdbc:mysql://localhost:3306/yggl";
private final static String username = "root";
private final static String password = "ziyexue";
public static void main(String args[]) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("OK");
}
try {
String url = "jdbc:mysql://localhost:3306/yggl" + "?useUnicode=true&characterEncoding=UTF-8&userSSL=true&serverTimezone=UTC";
Connection dbConn = DriverManager.getConnection(url, username, password);
Statement st = dbConn.createStatement();
System.out.println("连接数据库成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("SQL Server连接失败!");
}
}
}
```
阅读全文