我已经安装了WAMP的mysql服务器并创建了名为getataxi
的数据库。当我转到phpMyAdmin
时,我可以看到数据库及其表格。我还通过JDBC连接到这个数据库。当我使用:
conn = DriverManager.getConnection(DB_URL,USER,PASS);
我收到此错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:未知数据库'getataxi' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) 在com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
可能是什么问题?
注意:
jdbc:mysql://localhost/getataxi
我还尝试了jdbc:mysql://localhost:3306/getataxi
答案 0 :(得分:2)
以下简化案例适用于我在WAMP(USBWebserver)下,成功列出名为getataxi
的数据库中的所有表:
import java.sql.*;
public class mysqlTestMain {
public static void main(String[] args) {
Connection conn = null;
try {
String myConnectionString =
"jdbc:mysql://localhost:3306/getataxi?" +
"useUnicode=yes&characterEncoding=UTF-8";
conn = DriverManager.getConnection(myConnectionString, "root", "beer");
Statement stmt = conn.createStatement();
stmt.execute("SHOW TABLES");
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
如果相同的代码不适合您,请尝试使用以下代码列出服务器上的所有(可见)数据库:
import java.sql.*;
public class mysqlTestMain {
public static void main(String[] args) {
Connection conn = null;
try {
String myConnectionString =
"jdbc:mysql://localhost:3306?" +
"useUnicode=yes&characterEncoding=UTF-8";
conn = DriverManager.getConnection(myConnectionString, "root", "beer");
Statement stmt = conn.createStatement();
stmt.execute("SHOW DATABASES");
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
当我运行它时,我得到一个这样的列表:
information_schema
getataxi
mydb
mysql
performance_schema
test
答案 1 :(得分:0)
MySQL表和数据库对应于文件。因此,如果您使用Linux,则区分大小写(但不在Windows下)。
答案 2 :(得分:-1)
正如你所说,你有服务器了:
将以下代码保存为php文件并将其放在www文件夹中并尝试访问该页面
<?php
$username = "root";
$password = "your_password";
$hostname = "localhost:3306"; <==change port if different1
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
您应该可以在浏览器中看到“连接到MySQL”消息,以确认主机名,用户名和密码组合。
在Java代码中,
import java.sql.*;
public class Java2MySql
{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
System.out.println("Successfully connected");
} catch (Exception e) {
e.printStackTrace();
}
}
}
您看到成功连接没有任何错误。然后你的代码有问题。请正确检查您的代码。