检查下面代码错误package T1; import java.sql.Connection; import java.sql.DriverManager; public class t1 { public static void main(String[] args) { String driverName="com.mysql.jdbc.Driver"; String userName="root"; String userPwd="1234"; String dbName="student"; String url1="jdbc:mysql://localhost:3306/"+dbName; String url2="?user="+userName+"&password="+userPwd; String url3="&useUnicode=true&characterEncoding=UTF-8"; String url=url1+url2+url3; Class.forName(driverName); Connection conn=DriverManager.getConnection(url); } }
时间: 2023-06-08 15:05:36 浏览: 249
java+sql.rar_SQL java_java s_java sql_java sql 简单_java.sql.
" & "password=" userPwd "&useUnicode=true&characterEncoding=UTF8"; try { Class.forName(driverName); Connection conn=DriverManager.getConnection(url1+url2); System.out.println("连接成功!"); } catch (Exception e) { System.out.println("连接失败!"); e.printStackTrace(); } } }
您的代码错误在于一些符号的错误。
1. 第8行中,应该使用加号(+)将 dbName 拼接到 url1 后面。所以应该是:
String url1="jdbc:mysql://localhost:3306/" + dbName;
2. 第9行中,也应该使用加号(+)将 userName 和 userPwd 拼接到 url2 后面。所以应该是:
String url2="?user=" + userName + "&password=" + userPwd + "&useUnicode=true&characterEncoding=UTF8";
修正后的代码如下:
package T1;
import java.sql.Connection;
import java.sql.DriverManager;
public class t1 {
public static void main(String[] args) {
String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="1234";
String dbName="student";
String url1="jdbc:mysql://localhost:3306/" + dbName;
String url2="?user=" + userName + "&password=" + userPwd + "&useUnicode=true&characterEncoding=UTF8";
try {
Class.forName(driverName);
Connection conn=DriverManager.getConnection(url1+url2);
System.out.println("连接成功!");
} catch (Exception e) {
System.out.println("连接失败!");
e.printStackTrace();
}
}
}
希望这能帮助您解决问题。
阅读全文