我在我的Java类中有以下代码,但是我无法创建单个表,因为它不会选择数据库
//STEP 1. Import required packages
import java.sql.*;
public class DBTest {
// Database credentials
private static final String USER = "root";
private static final String PASS = "1234";
private static Connection conn = null;
private static Statement stmt = null;
static final String DB_URL = "jdbc:mysql://localhost/";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
getConnection();
}
public static Connection getConnection() throws SQLException, ClassNotFoundException {
try {
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
createTable(conn);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
return conn;
}
public static void createTable(Connection conn) throws SQLException {
System.out.println("Creating database...");
stmt = conn.createStatement();
// Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// Execute a query
System.out.println("Creating table in given database...");
String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), "
+ " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}
}
请注意:我仅导入了java.sql库,并且我已经在引用的库中获得了我的连接器,所以一切都应该设置好了!考虑到所有这些,请问有人能告诉我为什么会出现“未选择数据库”的SQLException吗?
DB_URL
的值是"jdbc:mysql://localhost/MyDatabase"
,它是用于连接本地MySQL数据库中名为"MyDatabase"的数据库的。 - ReimeuscreateTable
中创建一个新的服务器连接(没有数据库)? - Mark Rotteveel