英文:
Java JDBC: Cannot connect to SQL due to unknown database
问题
我已经能够通过Netbeans在我的旧电脑上连接到MySQL,使用以下代码:
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza?user=root";
Connection con = DriverManager.getConnection(connectionUrl,"root","root");
然而,自从我换了新电脑后,每次尝试运行该代码时,都会出现以下错误:
SQL 异常:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 未知数据库 'root'
作为一个相对新手的编程者,我尝试在线搜索不同的查询,但未能找到解决方案。
备注:
-
我尝试更改代码的不同部分,确保没有漏掉任何大写/小写字母。
-
我进入了MYSQL并运行了一个命令来检查所有数据库名称,并确保复制了正确的数据库名称。
-
无论我如何更改代码,它总是显示"未知数据库 'root'",即使我没有将root作为数据库名称输入。
任何帮助将不胜感激!
英文:
So I've been able to connect to MySQL through Netbeans on my older computer, using the following code:
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza?user=root";
Connection con = DriverManager.getConnection(connectionUrl,"root","root");
However, since getting a new computer, every time I try to run the code, it comes up with this error:
> SQL Exception:
> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
> database 'root'
Being fairly new to coding in general, I tried researching different queries online but couldn't come up with a solution.
Notes:
-I tried changing different sections of my code, making sure I didn't miss any upper case/lower case letters
-I went onto MYSQL and ran a command to check all the database names, and made sure to copy the right one down
-No matter how I change the code in anyway, it always says "unknown database 'root'" even though I haven't put root down as the database name
Any help would be greatly appreciated!
答案1
得分: 0
您的数据库URL不应包含?user=root
后缀。
请将其修改为以下形式,因为您已经在getConnection(url, username, password)
调用中指定了用户名/密码。
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
英文:
Your database URL should not have the ?user=root
suffix.
Make it look like so, as you are specifying the username/password already in the getConnection(url, username, password)
call.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
答案2
得分: 0
因为在创建con
对象时下一步需要用户名和密码,所以在连接url
中不应该指定它。
请尝试在连接url
中去除?user=root
,然后运行以下代码:
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
英文:
Since it is asking from username and password in next step while making con
object you should not specify it in connection url
.
Try to run code by removing the ?user=root
from your connection url
.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
答案3
得分: 0
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tblpizza","root","root");
尝试这种方式,你可以省略connectionUrl变量。
英文:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tblpizza","root","root");
Try this way, you can omit the connectionUrl variable.
专注分享java语言的经验与见解,让所有开发者获益!
评论